nanocodex-oai-api 0.3.0

Tower-native OpenAI Responses API and managed context for Nanocodex
Documentation
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
use std::{num::NonZeroU32, sync::Arc};

use ::tower::Layer;

mod config;
mod platform;

use crate::{
    DefaultResponsesService, OpenAiAuth, OpenAiAuthError, OpenAiAuthMode, ReasoningMode,
    ResponsesHistory, ResponsesRetryPolicy, ResponsesTransport, Thinking, session::SessionBuilder,
};

#[doc(hidden)]
pub use config::ModelConfig;
pub use config::ModelConfig as ResponsesServiceConfig;

/// Configured, cloneable `OpenAI` client recipe.
///
/// `OpenAi` owns authentication, endpoint policy, and the concrete Tower
/// service factory. Each session built from it receives independent mutable
/// service and conversation state.
#[derive(Clone)]
pub struct OpenAi<F = StandardServiceFactory> {
    config: ModelConfig,
    factory: F,
}

impl OpenAi<StandardServiceFactory> {
    /// Creates a client with the standard persistent WebSocket and retry
    /// stack, including session-scoped HTTPS fallback on native targets.
    ///
    /// # Errors
    ///
    /// Returns an error when the supplied credentials are unavailable.
    pub fn new(auth: impl Into<OpenAiAuth>) -> Result<Self, OpenAiError> {
        Self::builder(auth).build()
    }

    /// Starts configuring an `OpenAI` client.
    #[must_use]
    pub fn builder(auth: impl Into<OpenAiAuth>) -> OpenAiBuilder<StandardServiceFactory> {
        let auth = auth.into();
        let mode = auth.mode();
        let mut config = ModelConfig {
            auth,
            ..ModelConfig::default()
        };
        apply_mode_defaults(&mut config, mode);
        OpenAiBuilder {
            config,
            factory: StandardServiceFactory::default(),
        }
    }
}

impl<F> OpenAi<F>
where
    F: ResponsesServiceFactory,
{
    /// Starts a client-side managed session with stable developer
    /// instructions.
    ///
    /// The returned builder does not make a network request. Its `build`
    /// method creates fresh transport and context state.
    #[must_use]
    pub fn instructions(&self, instructions: impl Into<Arc<str>>) -> SessionBuilder<F> {
        SessionBuilder::new(self.clone(), instructions.into())
    }

    pub(crate) const fn config(&self) -> &ModelConfig {
        &self.config
    }

    pub(crate) fn make_service(&self) -> F::Service {
        self.factory.make(Arc::new(self.config.clone()))
    }

    pub(crate) fn into_parts(self) -> (ModelConfig, F) {
        (self.config, self.factory)
    }
}

/// Builder for a configured `OpenAI` client and concrete Tower service factory.
#[derive(Clone)]
pub struct OpenAiBuilder<F = StandardServiceFactory> {
    config: ModelConfig,
    factory: F,
}

impl<F> OpenAiBuilder<F> {
    /// Selects the initial Responses transport policy for new sessions.
    ///
    /// [`ResponsesTransport::WebSocket`] prefers a persistent socket. The
    /// native standard stack degrades one-way to HTTPS after exhausting its
    /// retry budget.
    /// [`ResponsesTransport::Https`] never probes the WebSocket endpoint.
    #[must_use]
    pub const fn transport(mut self, transport: ResponsesTransport) -> Self {
        self.config.responses_transport = transport;
        if matches!(transport, ResponsesTransport::Https) && !self.config.store_responses {
            self.config.responses_history = ResponsesHistory::FullReplay;
        }
        self
    }

    /// Selects incremental continuation or complete replay for healthy calls.
    #[must_use]
    pub const fn history(mut self, history: ResponsesHistory) -> Self {
        self.config.responses_history = history;
        self
    }

    /// Controls whether the provider retains Responses checkpoints.
    ///
    /// Storage is disabled by default for both API-key and ChatGPT
    /// authentication. API-key callers can opt into durable checkpoints with
    /// `store(true)`; ChatGPT subscription authentication does not support
    /// stored responses.
    ///
    /// On HTTPS, this also selects the compatible default history policy:
    /// incremental checkpoints when enabled and full client-history replay
    /// when disabled. Call [`Self::history`] afterwards to override that
    /// default.
    #[must_use]
    pub const fn store(mut self, store: bool) -> Self {
        self.config.store_responses = store;
        if matches!(self.config.responses_transport, ResponsesTransport::Https) {
            self.config.responses_history = if store {
                ResponsesHistory::Incremental
            } else {
                ResponsesHistory::FullReplay
            };
        }
        self
    }

    /// Sets the default reasoning effort for new sessions and agents.
    ///
    /// A higher-level session or agent builder may override this reusable
    /// client default without mutating the `OpenAi` recipe.
    #[must_use]
    pub const fn thinking(mut self, thinking: Thinking) -> Self {
        self.config.thinking = thinking;
        self
    }

    /// Sets the default reasoning execution mode for new sessions and agents.
    ///
    /// A higher-level agent builder may override this reusable client default.
    #[must_use]
    pub const fn reasoning_mode(mut self, reasoning_mode: ReasoningMode) -> Self {
        self.config.reasoning_mode = reasoning_mode;
        self
    }

    /// Selects the default priority-processing policy for new sessions and
    /// agents.
    ///
    /// A higher-level session or agent builder may override this reusable
    /// client default without mutating the `OpenAi` recipe.
    #[must_use]
    pub const fn fast_mode(mut self, enabled: bool) -> Self {
        self.config.fast_mode = enabled;
        self
    }

    /// Replaces the standard Responses WebSocket endpoint.
    #[must_use]
    pub fn websocket_url(mut self, url: impl Into<String>) -> Self {
        self.config.websocket_url = url.into();
        self
    }

    /// Replaces the standard `OpenAI` API base URL.
    #[must_use]
    pub fn api_base_url(mut self, url: impl Into<String>) -> Self {
        self.config.api_base_url = url.into();
        self
    }

    /// Installs the environment-owned socket and timer implementation.
    ///
    /// The host only moves text frames and waits for retry deadlines. Request
    /// encoding, response decoding, continuation state, and retry decisions
    /// remain owned by this crate.
    #[cfg(any(target_family = "wasm", docsrs))]
    #[cfg_attr(docsrs, doc(cfg(target_family = "wasm")))]
    #[must_use]
    pub fn host_transport(mut self, transport: impl crate::transport::host::HostTransport) -> Self {
        self.config.host_transport = Some(Arc::new(transport));
        self
    }

    /// Applies a Tower layer without boxing the resulting service.
    ///
    /// Common Tower middleware that returns [`tower::BoxError`] is converted
    /// into [`crate::ResponseError`] without discarding its source.
    ///
    /// ```
    /// use std::time::Duration;
    ///
    /// use nanocodex_oai_api::OpenAi;
    /// use tower::timeout::TimeoutLayer;
    ///
    /// let openai = OpenAi::builder("test-api-key")
    ///     .layer(TimeoutLayer::new(Duration::from_secs(45)))
    ///     .build()?;
    ///
    /// let session = openai
    ///     .instructions("Preserve exact identifiers and answer concisely.")
    ///     .build()?;
    /// assert_eq!(session.history_len(), 0);
    /// # Ok::<(), Box<dyn std::error::Error>>(())
    /// ```
    #[must_use]
    pub fn layer<L>(self, layer: L) -> OpenAiBuilder<LayeredServiceFactory<F, L>> {
        OpenAiBuilder {
            config: self.config,
            factory: LayeredServiceFactory {
                inner: self.factory,
                layer,
            },
        }
    }

    /// Replaces the standard stack with a factory for independent services.
    ///
    /// The factory runs once per managed session. Its service receives a
    /// replayable [`crate::tower::ResponsesAttempt`], may emit normalized
    /// streaming events through [`crate::tower::ResponsesAttempt::emit`], and
    /// returns one complete [`crate::tower::ResponsesServiceResponse`].
    ///
    /// ```no_run
    /// use nanocodex_oai_api::{
    ///     OpenAi, ResponseError, ResponseEvent,
    ///     responses::{ContentItem, MessageRole, ResponseItem},
    ///     tower::{
    ///         GenerationOutput, ResponsePipelineStats, ResponsesAttempt,
    ///         ResponsesOutput, ResponsesServiceResponse,
    ///     },
    /// };
    /// use tower::service_fn;
    ///
    /// # async fn run() -> Result<(), Box<dyn std::error::Error>> {
    /// let openai = OpenAi::builder("test-api-key")
    ///     .service(|| {
    ///         service_fn(|request: ResponsesAttempt| async move {
    ///             request
    ///                 .emit(ResponseEvent::OutputTextDelta(
    ///                     "served by the adapter".to_owned(),
    ///                 ))
    ///                 .await;
    ///             let item = ResponseItem::message(
    ///                 MessageRole::Assistant,
    ///                 [ContentItem::output_text("served by the adapter")],
    ///             );
    ///             Ok::<_, ResponseError>(ResponsesServiceResponse::new(
    ///                 ResponsesOutput::Generation(GenerationOutput {
    ///                     id: "resp_adapter_01".to_owned(),
    ///                     status: "completed".to_owned(),
    ///                     end_turn: Some(true),
    ///                     final_message: Some("served by the adapter".to_owned()),
    ///                     output_items: vec![item],
    ///                     code_calls: Vec::new(),
    ///                     usage: None,
    ///                     time_to_first_event_ns: 0,
    ///                     time_to_first_output_ns: Some(0),
    ///                     pipeline_stats: ResponsePipelineStats::default(),
    ///                 }),
    ///             ))
    ///         })
    ///     })
    ///     .build()?;
    /// let mut session = openai
    ///     .instructions("Return the adapter's exact retained result.")
    ///     .build()?;
    ///
    /// let completed = session
    ///     .turn()
    ///     .create("Return the retained result.")
    ///     .await?;
    /// assert_eq!(completed.output_text(), "served by the adapter");
    /// # Ok(())
    /// # }
    /// ```
    #[must_use]
    pub fn service<M>(self, make: M) -> OpenAiBuilder<CallerServiceFactory<M>> {
        OpenAiBuilder {
            config: self.config,
            factory: CallerServiceFactory {
                make: Arc::new(make),
            },
        }
    }
}

impl OpenAiBuilder<StandardServiceFactory> {
    /// Sets the total attempt limit for the standard typed retry policy.
    #[must_use]
    pub const fn max_attempts(mut self, max_attempts: NonZeroU32) -> Self {
        self.factory.max_attempts = max_attempts;
        self
    }

    /// Replaces the HTTP client used by the standard HTTPS/SSE transport.
    #[cfg(not(target_family = "wasm"))]
    #[cfg_attr(docsrs, doc(cfg(not(target_family = "wasm"))))]
    #[must_use]
    pub fn http_client(mut self, client: reqwest::Client) -> Self {
        self.factory.platform.set_http_client(client);
        self
    }
}

impl<F> OpenAiBuilder<F>
where
    F: ResponsesServiceFactory,
{
    /// Validates the configuration and returns a cloneable client recipe.
    ///
    /// # Errors
    ///
    /// Returns an error for unavailable credentials or an incompatible
    /// transport, storage, and replay configuration.
    pub fn build(self) -> Result<OpenAi<F>, OpenAiError> {
        validate(&self.config)?;
        self.factory.validate_config(&self.config)?;
        Ok(OpenAi {
            config: self.config,
            factory: self.factory,
        })
    }
}

/// Standard service factory for the persistent transport and typed retry
/// stack.
#[derive(Clone)]
pub struct StandardServiceFactory {
    max_attempts: NonZeroU32,
    platform: platform::FactoryPlatform,
}

impl Default for StandardServiceFactory {
    fn default() -> Self {
        Self {
            max_attempts: ResponsesRetryPolicy::DEFAULT_MAX_ATTEMPTS,
            platform: platform::FactoryPlatform::new(),
        }
    }
}

/// Factory produced by [`OpenAiBuilder::service`].
///
/// The callable is invoked once for each managed session, so every session
/// owns independent mutable Tower service state.
pub struct CallerServiceFactory<M> {
    make: Arc<M>,
}

impl<M> Clone for CallerServiceFactory<M> {
    fn clone(&self) -> Self {
        Self {
            make: Arc::clone(&self.make),
        }
    }
}

/// A concrete Tower layer applied to another service factory.
#[derive(Clone)]
pub struct LayeredServiceFactory<F, L> {
    inner: F,
    layer: L,
}

/// Factory for the concrete Tower service owned by each managed session.
///
/// This trait makes the generic result of [`OpenAiBuilder::layer`] and
/// [`OpenAiBuilder::service`] usable in named structs and function bounds.
/// Most callers should obtain one of the provided implementations from those
/// builder methods instead of implementing the construction boundary directly.
pub trait ResponsesServiceFactory: Clone {
    /// Concrete service owned by each managed session.
    type Service;

    /// Validates service-specific client configuration.
    fn validate_config(&self, _config: &ResponsesServiceConfig) -> Result<(), OpenAiError> {
        Ok(())
    }

    /// Creates one independent service stack.
    fn make(&self, config: Arc<ResponsesServiceConfig>) -> Self::Service;
}

impl ResponsesServiceFactory for StandardServiceFactory {
    type Service = DefaultResponsesService;

    fn validate_config(&self, config: &ModelConfig) -> Result<(), OpenAiError> {
        self.platform.validate_config(config)
    }

    fn make(&self, config: Arc<ModelConfig>) -> Self::Service {
        self.platform.make(config, self.max_attempts)
    }
}

impl<M, S> ResponsesServiceFactory for CallerServiceFactory<M>
where
    M: Fn() -> S,
{
    type Service = S;

    fn make(&self, _config: Arc<ModelConfig>) -> Self::Service {
        (self.make)()
    }
}

impl<F, L> ResponsesServiceFactory for LayeredServiceFactory<F, L>
where
    F: ResponsesServiceFactory,
    L: Layer<F::Service> + Clone,
{
    type Service = L::Service;

    fn validate_config(&self, config: &ModelConfig) -> Result<(), OpenAiError> {
        self.inner.validate_config(config)
    }

    fn make(&self, config: Arc<ModelConfig>) -> Self::Service {
        self.layer.layer(self.inner.make(config))
    }
}

/// Invalid `OpenAI` client configuration.
#[derive(Debug, thiserror::Error)]
pub enum OpenAiError {
    /// Credentials cannot currently provide an authorization value.
    #[error(transparent)]
    Authorization(#[from] OpenAiAuthError),
    /// Two client policies cannot be satisfied together.
    #[error("invalid OpenAI client configuration: {detail}")]
    InvalidConfiguration {
        /// Human-readable explanation without credentials.
        detail: &'static str,
    },
}

fn apply_mode_defaults(config: &mut ModelConfig, mode: OpenAiAuthMode) {
    config.store_responses = false;
    config.responses_history = ResponsesHistory::Incremental;
    mode.default_websocket_url()
        .clone_into(&mut config.websocket_url);
    mode.default_api_base_url()
        .clone_into(&mut config.api_base_url);
}

fn validate(config: &ModelConfig) -> Result<(), OpenAiError> {
    config.auth.validate()?;
    if config.websocket_url.trim().is_empty() {
        return Err(OpenAiError::InvalidConfiguration {
            detail: "the Responses WebSocket URL must not be empty",
        });
    }
    if config.api_base_url.trim().is_empty() {
        return Err(OpenAiError::InvalidConfiguration {
            detail: "the OpenAI API base URL must not be empty",
        });
    }
    if config.auth.mode() == OpenAiAuthMode::ChatGpt && config.store_responses {
        return Err(OpenAiError::InvalidConfiguration {
            detail: "ChatGPT subscription authentication does not support store: true",
        });
    }
    if matches!(config.responses_transport, ResponsesTransport::Https)
        && !config.store_responses
        && matches!(config.responses_history, ResponsesHistory::Incremental)
    {
        return Err(OpenAiError::InvalidConfiguration {
            detail: "HTTPS with store: false requires full client-history replay",
        });
    }
    Ok(())
}

#[cfg(test)]
mod tests {
    use std::{
        convert::Infallible,
        error::Error as _,
        future::{Ready, pending},
        time::Duration,
    };

    use ::tower::{Service, service_fn, timeout::TimeoutLayer};

    use crate::{
        ModelConfig, OpenAiAuthMode, ResponseError, ResponsesAttempt, ResponsesHistory,
        ResponsesServiceResponse, ResponsesTransport,
    };

    use super::{OpenAi, apply_mode_defaults};

    #[derive(Clone)]
    struct NeverCalled;

    impl Service<ResponsesAttempt> for NeverCalled {
        type Response = ResponsesServiceResponse;
        type Error = Infallible;
        type Future = Ready<Result<Self::Response, Self::Error>>;

        fn poll_ready(
            &mut self,
            _context: &mut std::task::Context<'_>,
        ) -> std::task::Poll<Result<(), Self::Error>> {
            std::task::Poll::Ready(Ok(()))
        }

        fn call(&mut self, _request: ResponsesAttempt) -> Self::Future {
            panic!("test service should not be called")
        }
    }

    #[test]
    fn one_client_recipe_builds_independent_sessions() {
        let client = OpenAi::builder("test-key")
            .service(|| NeverCalled)
            .build()
            .unwrap();

        let session = client.instructions("Answer only from supplied facts.");
        let first = session.clone().build().unwrap();
        let second = session.build().unwrap();

        assert_ne!(first.id(), second.id());
    }

    #[test]
    fn response_storage_is_opt_in_for_both_auth_modes() {
        for mode in [OpenAiAuthMode::ApiKey, OpenAiAuthMode::ChatGpt] {
            let mut config = ModelConfig {
                store_responses: true,
                ..ModelConfig::default()
            };
            apply_mode_defaults(&mut config, mode);
            assert!(!config.store_responses);
        }
    }

    #[test]
    fn api_key_can_opt_into_https_checkpoints() {
        let client = OpenAi::builder("test-key")
            .transport(ResponsesTransport::Https)
            .store(true)
            .build()
            .unwrap();

        assert!(client.config.store_responses);
        assert_eq!(
            client.config.responses_history,
            ResponsesHistory::Incremental
        );
    }

    #[tokio::test]
    async fn tower_box_errors_remain_usable_through_the_managed_response_api() {
        let client = OpenAi::builder("test-key")
            .service(|| {
                service_fn(|_request: ResponsesAttempt| {
                    pending::<Result<ResponsesServiceResponse, ResponseError>>()
                })
            })
            .layer(TimeoutLayer::new(Duration::from_millis(1)))
            .build()
            .unwrap();
        let mut session = client
            .instructions("Return exactly one short answer.")
            .build()
            .unwrap();

        let error = session
            .turn()
            .create("This request should reach the test deadline.")
            .await
            .unwrap_err();

        assert!(error.source().is_some());
        assert!(error.to_string().contains("request timed out"));
    }
}