openai-ergonomic 0.22.0

Ergonomic Rust wrapper for OpenAI API
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
//! Langfuse interceptor for OpenTelemetry-based LLM observability.
//!
//! This interceptor automatically instruments `OpenAI` API calls with OpenTelemetry spans.
//! You must configure the OpenTelemetry tracer with Langfuse exporter separately.
//!
//! # Usage
//!
//! ```no_run
//! # use openai_ergonomic::{Builder, Client};
//! # use openai_ergonomic::langfuse_interceptor::{LangfuseInterceptor, LangfuseConfig};
//! # use openai_ergonomic::langfuse_exporter_from_env;
//! # use opentelemetry_sdk::runtime::Tokio;
//! # use opentelemetry_sdk::trace::span_processor_with_async_runtime::BatchSpanProcessor;
//! # use opentelemetry_sdk::trace::SdkTracerProvider;
//! # use opentelemetry::global;
//! # use opentelemetry::trace::TracerProvider;
//! # async fn example() -> Result<(), Box<dyn std::error::Error>> {
//! // 1. Build Langfuse exporter
//! let exporter = langfuse_exporter_from_env()?;
//!
//! // 2. Create tracer provider
//! let provider = SdkTracerProvider::builder()
//!     .with_span_processor(BatchSpanProcessor::builder(exporter, Tokio).build())
//!     .build();
//!
//! global::set_tracer_provider(provider.clone());
//!
//! // 3. Create interceptor with tracer
//! let tracer = provider.tracer("openai-ergonomic");
//! let interceptor = LangfuseInterceptor::new(tracer, LangfuseConfig::new());
//! let client = Client::from_env()?
//!     .with_interceptor(interceptor)
//!     .build();
//!
//! // Traces are automatically sent to Langfuse
//! let response = client.send_chat(client.chat_simple("Hello!")).await?;
//! # Ok(())
//! # }
//! ```

use crate::interceptor::{
    AfterResponseContext, BeforeRequestContext, ErrorContext, Interceptor, StreamChunkContext,
    StreamEndContext, StreamTerminalContext,
};
use crate::langfuse_context::LangfuseContext;
use crate::Result;
use opentelemetry::{
    trace::{SpanKind, Status, Tracer},
    KeyValue,
};
use opentelemetry_semantic_conventions::attribute::{
    GEN_AI_OPERATION_NAME, GEN_AI_REQUEST_MAX_TOKENS, GEN_AI_REQUEST_MODEL,
    GEN_AI_REQUEST_TEMPERATURE, GEN_AI_RESPONSE_ID, GEN_AI_SYSTEM, GEN_AI_USAGE_INPUT_TOKENS,
    GEN_AI_USAGE_OUTPUT_TOKENS,
};
use serde_json::Value;
use std::future::Future;
use std::sync::{Arc, Mutex};
use tracing::{debug, error, info};

/// State managed by the Langfuse interceptor across the request lifecycle.
///
/// This state is passed through the interceptor hooks to maintain
/// span information without requiring global state.
///
/// Uses `Mutex` for interior mutability to ensure thread-safety in async contexts.
///
/// The generic type `S` is the Span type from the tracer.
pub struct LangfuseState<S = opentelemetry::global::BoxedSpan> {
    /// The active span for this request (uses Mutex for thread-safe interior mutability)
    pub(crate) span: Mutex<Option<S>>,
}

impl<S> Default for LangfuseState<S> {
    fn default() -> Self {
        Self {
            span: Mutex::new(None),
        }
    }
}

/// Configuration for the Langfuse interceptor.
#[derive(Debug, Clone)]
pub struct LangfuseConfig {
    /// Enable debug logging
    pub debug: bool,
}

impl Default for LangfuseConfig {
    fn default() -> Self {
        Self {
            debug: std::env::var("LANGFUSE_DEBUG")
                .unwrap_or_else(|_| "false".to_string())
                .parse()
                .unwrap_or(false),
        }
    }
}

impl LangfuseConfig {
    /// Create a new configuration.
    pub fn new() -> Self {
        Self::default()
    }

    /// Enable debug logging.
    #[must_use]
    pub fn with_debug(mut self, debug: bool) -> Self {
        self.debug = debug;
        self
    }
}

/// Langfuse interceptor for OpenTelemetry-based observability.
///
/// This interceptor automatically creates spans for API calls.
/// Spans are maintained across `before_request` and `after_response` using a global registry
/// and request metadata, requiring no user code changes.
///
/// The tracer must be configured externally - this interceptor only instruments API calls.
pub struct LangfuseInterceptor<T: Tracer + Send + Sync> {
    config: LangfuseConfig,
    tracer: Arc<T>,
    context: Arc<LangfuseContext>,
}

impl<T: Tracer + Send + Sync> LangfuseInterceptor<T>
where
    T::Span: Send + Sync + 'static,
{
    /// Create a new Langfuse interceptor with the given tracer.
    ///
    /// The tracer should be configured to export to Langfuse using
    /// [`crate::langfuse_exporter_from_env`].
    ///
    /// # Example
    ///
    /// ```no_run
    /// use opentelemetry::global;
    /// use opentelemetry::trace::TracerProvider;
    /// use openai_ergonomic::langfuse_exporter_from_env;
    /// use opentelemetry_sdk::runtime::Tokio;
    /// use opentelemetry_sdk::trace::span_processor_with_async_runtime::BatchSpanProcessor;
    /// use opentelemetry_sdk::trace::SdkTracerProvider;
    ///
    /// # async fn setup() -> Result<(), Box<dyn std::error::Error>> {
    /// // Build exporter
    /// let exporter = langfuse_exporter_from_env()?;
    ///
    /// // Create tracer provider with batch processor
    /// let provider = SdkTracerProvider::builder()
    ///     .with_span_processor(BatchSpanProcessor::builder(exporter, Tokio).build())
    ///     .build();
    ///
    /// // Set as global provider
    /// global::set_tracer_provider(provider.clone());
    ///
    /// // Get tracer for interceptor
    /// let tracer = provider.tracer("openai-ergonomic");
    ///
    /// // Create interceptor with tracer
    /// use openai_ergonomic::langfuse_interceptor::{LangfuseInterceptor, LangfuseConfig};
    /// let interceptor = LangfuseInterceptor::new(tracer, LangfuseConfig::new());
    /// # Ok(())
    /// # }
    /// ```
    pub fn new(tracer: T, config: LangfuseConfig) -> Self {
        if config.debug {
            info!("Langfuse interceptor initialized");
        }

        Self {
            config,
            tracer: Arc::new(tracer),
            context: Arc::new(LangfuseContext::new()),
        }
    }

    /// Set the session ID for traces created by this interceptor.
    pub fn set_session_id(&self, session_id: impl Into<String>) {
        self.context.set_session_id(session_id);
    }

    /// Set the user ID for traces created by this interceptor.
    pub fn set_user_id(&self, user_id: impl Into<String>) {
        self.context.set_user_id(user_id);
    }

    /// Add tags to traces created by this interceptor.
    pub fn add_tags(&self, tags: Vec<String>) {
        self.context.add_tags(tags);
    }

    /// Add a single tag to traces created by this interceptor.
    pub fn add_tag(&self, tag: impl Into<String>) {
        self.context.add_tag(tag);
    }

    /// Set metadata for traces created by this interceptor.
    pub fn set_metadata(&self, metadata: serde_json::Value) {
        self.context.set_metadata(metadata);
    }

    /// Clear all context attributes.
    pub fn clear_context(&self) {
        self.context.clear();
    }

    /// Get a reference to the Langfuse context.
    pub fn context(&self) -> &Arc<LangfuseContext> {
        &self.context
    }

    /// Extract request parameters from JSON.
    fn extract_request_params(request_json: &str) -> serde_json::Result<Value> {
        serde_json::from_str(request_json)
    }
}

// The hooks only record spans synchronously; the trait impl below wraps them in
// ready futures. They keep the `Interceptor` hook signatures, hence the allows.
#[allow(
    clippy::unnecessary_wraps,
    clippy::unused_self,
    clippy::needless_pass_by_ref_mut
)]
impl<T: Tracer + Send + Sync> LangfuseInterceptor<T>
where
    T::Span: Send + Sync + 'static,
{
    fn record_before_request(
        &self,
        ctx: &mut BeforeRequestContext<'_, LangfuseState<T::Span>>,
    ) -> Result<()> {
        let tracer = self.tracer.as_ref();

        // Build initial attributes
        let mut attributes = vec![
            KeyValue::new(GEN_AI_SYSTEM, "openai"),
            KeyValue::new(GEN_AI_OPERATION_NAME, ctx.operation.to_string()),
            KeyValue::new(GEN_AI_REQUEST_MODEL, ctx.model.to_string()),
        ];

        // Add Langfuse context attributes from this interceptor's context
        attributes.extend(self.context.get_attributes());

        // Parse request JSON and add relevant attributes
        if let Ok(params) = Self::extract_request_params(ctx.request_json) {
            if let Some(temperature) = params
                .get("temperature")
                .and_then(serde_json::Value::as_f64)
            {
                attributes.push(KeyValue::new(GEN_AI_REQUEST_TEMPERATURE, temperature));
            }
            // `max_output_tokens` for the Responses API
            if let Some(max_tokens) = params
                .get("max_tokens")
                .or_else(|| params.get("max_output_tokens"))
                .and_then(serde_json::Value::as_i64)
            {
                attributes.push(KeyValue::new(GEN_AI_REQUEST_MAX_TOKENS, max_tokens));
            }

            // Add messages as gen_ai.prompt attributes
            for (i, (role, content)) in prompt_messages(&params).into_iter().enumerate() {
                attributes.push(KeyValue::new(format!("gen_ai.prompt.{i}.role"), role));
                attributes.push(KeyValue::new(format!("gen_ai.prompt.{i}.content"), content));
            }
        }

        // Create span and store it in state
        let span = tracer
            .span_builder(ctx.operation.to_string())
            .with_kind(SpanKind::Client)
            .with_attributes(attributes)
            .start(tracer);

        // Store span directly in state
        *ctx.state
            .span
            .lock()
            .unwrap_or_else(std::sync::PoisonError::into_inner) = Some(span);

        if self.config.debug {
            debug!("Started Langfuse span for operation: {}", ctx.operation);
        }

        Ok(())
    }

    fn record_after_response(
        &self,
        ctx: &AfterResponseContext<'_, LangfuseState<T::Span>>,
    ) -> Result<()> {
        use opentelemetry::trace::Span;

        // Take the span from state so we can end it
        let Some(mut span) = ctx
            .state
            .span
            .lock()
            .unwrap_or_else(std::sync::PoisonError::into_inner)
            .take()
        else {
            if self.config.debug {
                debug!("No span found in state for operation: {}", ctx.operation);
            }
            return Ok(());
        };

        // Add response attributes to the span

        #[allow(clippy::cast_possible_truncation)]
        {
            span.set_attribute(KeyValue::new(
                "duration_ms",
                ctx.duration.as_millis() as i64,
            ));
        }

        // Add usage metrics if available
        if let Some(input_tokens) = ctx.input_tokens {
            span.set_attribute(KeyValue::new(GEN_AI_USAGE_INPUT_TOKENS, input_tokens));
        }
        if let Some(output_tokens) = ctx.output_tokens {
            span.set_attribute(KeyValue::new(GEN_AI_USAGE_OUTPUT_TOKENS, output_tokens));
        }

        // Parse response and add completion content
        if let Ok(response) = Self::extract_request_params(ctx.response_json) {
            // Add response ID if available
            if let Some(id) = response.get("id").and_then(serde_json::Value::as_str) {
                span.set_attribute(KeyValue::new(GEN_AI_RESPONSE_ID, id.to_string()));
            }

            // The output messages of a Responses API response
            if let Some(output) = response.get("output").and_then(serde_json::Value::as_array) {
                let messages = output.iter().filter(|item| {
                    item.get("type").and_then(serde_json::Value::as_str) == Some("message")
                });
                for (i, message) in messages.enumerate() {
                    span.set_attribute(KeyValue::new(
                        format!("gen_ai.completion.{i}.role"),
                        "assistant",
                    ));
                    span.set_attribute(KeyValue::new(
                        format!("gen_ai.completion.{i}.content"),
                        content_text(message.get("content")),
                    ));
                }
            }

            // Add completion content
            if let Some(choices) = response
                .get("choices")
                .and_then(serde_json::Value::as_array)
            {
                for (i, choice) in choices.iter().enumerate() {
                    if let Some(message) = choice.get("message") {
                        if let Some(role) = message.get("role").and_then(serde_json::Value::as_str)
                        {
                            span.set_attribute(KeyValue::new(
                                format!("gen_ai.completion.{i}.role"),
                                role.to_string(),
                            ));
                        }
                        if let Some(content) =
                            message.get("content").and_then(serde_json::Value::as_str)
                        {
                            span.set_attribute(KeyValue::new(
                                format!("gen_ai.completion.{i}.content"),
                                content.to_string(),
                            ));
                        }
                    }
                }
            }
        }

        // End the span
        span.end();

        if self.config.debug {
            debug!("Completed Langfuse span for operation: {}", ctx.operation);
        }

        Ok(())
    }

    fn record_on_stream_chunk(
        &self,
        _ctx: &StreamChunkContext<'_, LangfuseState<T::Span>>,
    ) -> Result<()> {
        // Stream chunks can add attributes to the current span if needed
        // For now, we just let them pass through
        Ok(())
    }

    fn record_on_stream_end(
        &self,
        ctx: &StreamEndContext<'_, LangfuseState<T::Span>>,
    ) -> Result<()> {
        use opentelemetry::trace::Span;

        // Take the span from state so we can end it
        let Some(mut span) = ctx
            .state
            .span
            .lock()
            .unwrap_or_else(std::sync::PoisonError::into_inner)
            .take()
        else {
            if self.config.debug {
                debug!(
                    "No span found in state for stream operation: {}",
                    ctx.operation
                );
            }
            return Ok(());
        };

        // Add final streaming attributes

        #[allow(clippy::cast_possible_truncation, clippy::cast_possible_wrap)]
        {
            span.set_attribute(KeyValue::new(
                "stream.total_chunks",
                ctx.total_chunks as i64,
            ));
            span.set_attribute(KeyValue::new(
                "stream.duration_ms",
                ctx.duration.as_millis() as i64,
            ));
        }

        if let Some(input_tokens) = ctx.input_tokens {
            span.set_attribute(KeyValue::new(GEN_AI_USAGE_INPUT_TOKENS, input_tokens));
        }
        if let Some(output_tokens) = ctx.output_tokens {
            span.set_attribute(KeyValue::new(GEN_AI_USAGE_OUTPUT_TOKENS, output_tokens));
        }

        // End the span
        span.end();

        if self.config.debug {
            info!(
                "Completed streaming span for operation: {} with {} chunks",
                ctx.operation, ctx.total_chunks
            );
        }

        Ok(())
    }

    fn record_on_stream_terminal(
        &self,
        ctx: &StreamTerminalContext<'_, LangfuseState<T::Span>>,
    ) -> Result<()> {
        use opentelemetry::trace::Span;

        if matches!(ctx.outcome, crate::streaming::StreamOutcome::Completed) {
            return self.record_on_stream_end(&ctx.summary);
        }

        let Some(mut span) = ctx
            .summary
            .state
            .span
            .lock()
            .unwrap_or_else(std::sync::PoisonError::into_inner)
            .take()
        else {
            if self.config.debug {
                debug!(
                    "No span found for terminal stream event: {}",
                    ctx.summary.operation
                );
            }
            return Ok(());
        };

        #[allow(clippy::cast_possible_truncation, clippy::cast_possible_wrap)]
        {
            span.set_attribute(KeyValue::new(
                "stream.total_chunks",
                ctx.summary.total_chunks as i64,
            ));
            span.set_attribute(KeyValue::new(
                "stream.duration_ms",
                ctx.summary.duration.as_millis() as i64,
            ));
        }
        span.set_attribute(KeyValue::new(
            "stream.outcome",
            match ctx.outcome {
                crate::streaming::StreamOutcome::Completed => "completed",
                crate::streaming::StreamOutcome::StreamFailed(_) => "failed",
                crate::streaming::StreamOutcome::Cancelled => "cancelled",
            },
        ));
        if let Some(input_tokens) = ctx.summary.input_tokens {
            span.set_attribute(KeyValue::new(GEN_AI_USAGE_INPUT_TOKENS, input_tokens));
        }
        if let Some(output_tokens) = ctx.summary.output_tokens {
            span.set_attribute(KeyValue::new(GEN_AI_USAGE_OUTPUT_TOKENS, output_tokens));
        }

        let description = match ctx.outcome {
            crate::streaming::StreamOutcome::StreamFailed(failure) => {
                format!("stream failed ({:?})", failure.kind)
            }
            crate::streaming::StreamOutcome::Cancelled => "stream cancelled".to_string(),
            crate::streaming::StreamOutcome::Completed => unreachable!(),
        };
        span.set_status(Status::error(description));
        span.end();
        if self.config.debug {
            info!(
                "Finished streaming span for operation {} with outcome {:?}",
                ctx.summary.operation, ctx.outcome
            );
        }
        Ok(())
    }

    fn record_on_error(&self, ctx: &ErrorContext<'_, LangfuseState<T::Span>>) {
        use opentelemetry::trace::{Span, Status};

        // Take the span from state if available
        let Some(state) = ctx.state else {
            if self.config.debug {
                debug!(
                    "No state available for error in operation: {}",
                    ctx.operation
                );
            }
            return;
        };

        let Some(mut span) = state
            .span
            .lock()
            .unwrap_or_else(std::sync::PoisonError::into_inner)
            .take()
        else {
            if self.config.debug {
                debug!(
                    "No span found in state for error in operation: {}",
                    ctx.operation
                );
            }
            return;
        };

        // Set the span status to error
        span.set_status(Status::error(ctx.error.to_string()));

        // Add error attributes to the span
        span.set_attribute(KeyValue::new("error.type", format!("{:?}", ctx.error)));
        span.set_attribute(KeyValue::new("error.message", ctx.error.to_string()));

        if let Some(model) = ctx.model {
            span.set_attribute(KeyValue::new(GEN_AI_REQUEST_MODEL, model.to_string()));
        }

        // End the span
        span.end();

        if self.config.debug {
            error!(
                "Recorded error for operation {}: {}",
                ctx.operation, ctx.error
            );
        }
    }
}

impl<T: Tracer + Send + Sync> Interceptor<LangfuseState<T::Span>> for LangfuseInterceptor<T>
where
    T::Span: Send + Sync + 'static,
{
    fn before_request(
        &self,
        ctx: &mut BeforeRequestContext<'_, LangfuseState<T::Span>>,
    ) -> impl Future<Output = Result<()>> + Send {
        std::future::ready(self.record_before_request(ctx))
    }

    fn after_response(
        &self,
        ctx: &AfterResponseContext<'_, LangfuseState<T::Span>>,
    ) -> impl Future<Output = Result<()>> + Send {
        std::future::ready(self.record_after_response(ctx))
    }

    fn on_stream_chunk(
        &self,
        ctx: &StreamChunkContext<'_, LangfuseState<T::Span>>,
    ) -> impl Future<Output = Result<()>> + Send {
        std::future::ready(self.record_on_stream_chunk(ctx))
    }

    fn on_stream_end(
        &self,
        ctx: &StreamEndContext<'_, LangfuseState<T::Span>>,
    ) -> impl Future<Output = Result<()>> + Send {
        std::future::ready(self.record_on_stream_end(ctx))
    }

    fn on_stream_terminal(
        &self,
        ctx: &StreamTerminalContext<'_, LangfuseState<T::Span>>,
    ) -> impl Future<Output = Result<()>> + Send {
        std::future::ready(self.record_on_stream_terminal(ctx))
    }

    fn on_error(
        &self,
        ctx: &ErrorContext<'_, LangfuseState<T::Span>>,
    ) -> impl Future<Output = ()> + Send {
        self.record_on_error(ctx);
        std::future::ready(())
    }
}

// `Arc<LangfuseInterceptor<T>>` implements `Interceptor` through the blanket
// `Arc<I>` forwarding implementation in `crate::interceptor`.

/// The prompt messages of a request, as (role, content): the `messages` of a chat completion,
/// or the `instructions` and `input` of a Responses API request.
fn prompt_messages(params: &serde_json::Value) -> Vec<(String, String)> {
    let mut prompt = Vec::new();
    if let Some(messages) = params.get("messages").and_then(serde_json::Value::as_array) {
        for message in messages.iter().filter(|message| message.is_object()) {
            prompt.push(role_and_content(message, "unknown"));
        }
        return prompt;
    }
    if let Some(instructions) = params
        .get("instructions")
        .and_then(serde_json::Value::as_str)
    {
        prompt.push(("system".to_string(), instructions.to_string()));
    }
    match params.get("input") {
        Some(serde_json::Value::String(text)) => prompt.push(("user".to_string(), text.clone())),
        Some(serde_json::Value::Array(items)) => {
            for item in items.iter().filter(|item| item.get("role").is_some()) {
                prompt.push(role_and_content(item, "user"));
            }
        }
        _ => {}
    }
    prompt
}

fn role_and_content(message: &serde_json::Value, default_role: &str) -> (String, String) {
    let role = message
        .get("role")
        .and_then(serde_json::Value::as_str)
        .unwrap_or(default_role)
        .to_string();
    (role, content_text(message.get("content")))
}

/// The text of a message's content: a string, or the text of its parts.
fn content_text(content: Option<&serde_json::Value>) -> String {
    match content {
        Some(serde_json::Value::String(text)) => text.clone(),
        Some(serde_json::Value::Array(parts)) => parts
            .iter()
            .filter_map(|part| part.get("text").and_then(serde_json::Value::as_str))
            .collect(),
        _ => String::new(),
    }
}

#[cfg(test)]
mod tests {
    #![allow(clippy::unwrap_used, clippy::expect_used, clippy::panic)]
    use super::*;
    use crate::streaming::StreamOutcome;
    use opentelemetry::trace::noop::NoopTracer;
    use std::time::Duration;

    #[test]
    fn test_config_from_env() {
        std::env::set_var("LANGFUSE_DEBUG", "true");

        let config = LangfuseConfig::default();
        assert!(config.debug);

        // Cleanup
        std::env::remove_var("LANGFUSE_DEBUG");
    }

    #[test]
    fn prompt_messages_of_chat_and_responses_requests() {
        let chat = serde_json::json!({"messages": [
            {"role": "system", "content": "Be brief"},
            {"role": "user", "content": [{"type": "text", "text": "Hi"}]}
        ]});
        assert_eq!(
            prompt_messages(&chat),
            [
                ("system".to_string(), "Be brief".to_string()),
                ("user".to_string(), "Hi".to_string())
            ]
        );
        let responses = serde_json::json!({
            "instructions": "Be brief",
            "input": [
                {"type": "message", "role": "user", "content": "Hi"},
                {"type": "function_call_output", "call_id": "c", "output": "x"}
            ]
        });
        assert_eq!(
            prompt_messages(&responses),
            [
                ("system".to_string(), "Be brief".to_string()),
                ("user".to_string(), "Hi".to_string())
            ]
        );
        let text = serde_json::json!({"input": "Hello"});
        assert_eq!(
            prompt_messages(&text),
            [("user".to_string(), "Hello".to_string())]
        );
    }

    #[test]
    fn test_interceptor_creation() {
        let tracer = NoopTracer::new();
        let config = LangfuseConfig::new().with_debug(true);
        let _interceptor = LangfuseInterceptor::new(tracer, config);
        // No assertion needed - just verify it compiles and constructs
    }

    #[tokio::test]
    async fn terminal_failure_removes_active_langfuse_span() {
        let interceptor = LangfuseInterceptor::new(NoopTracer::new(), LangfuseConfig::new());
        let mut state = LangfuseState::default();
        let mut before = BeforeRequestContext {
            operation: "chat",
            model: "mock-model",
            request_json: "{}",
            state: &mut state,
        };
        interceptor.before_request(&mut before).await.unwrap();

        let summary = StreamEndContext {
            operation: "chat",
            model: "mock-model",
            request_json: "{}",
            total_chunks: 2,
            duration: Duration::from_millis(12),
            input_tokens: Some(3),
            output_tokens: Some(4),
            state: &state,
        };
        let terminal = StreamTerminalContext {
            summary,
            outcome: StreamOutcome::Cancelled,
        };
        interceptor.on_stream_terminal(&terminal).await.unwrap();
        assert!(state.span.lock().unwrap().is_none());
    }
}