Skip to main content

novel_openai/
traits.rs

1use reqwest::header::HeaderMap;
2use serde::Serialize;
3
4use crate::RequestOptions;
5use crate::error::OpenAIError;
6
7pub trait AsyncTryFrom<T>: Sized {
8    /// The type returned in the event of a conversion error.
9    type Error;
10
11    /// Performs the conversion.
12    fn try_from(value: T) -> impl std::future::Future<Output = Result<Self, Self::Error>> + Send;
13}
14
15/// Trait for events to get their event type string.
16pub trait EventType {
17    /// Returns the event type string (e.g., "batch.cancelled")
18    fn event_type(&self) -> &'static str;
19}
20
21/// Trait for events to get their event ID.
22pub trait EventId {
23    /// Returns the event ID
24    fn event_id(&self) -> &str;
25}
26
27/// Trait for types that can build RequestOptions through fluent API
28pub trait RequestOptionsBuilder: Sized {
29    /// Get mutable reference to RequestOptions (for building)
30    fn options_mut(&mut self) -> &mut RequestOptions;
31
32    /// Get reference to RequestOptions
33    fn options(&self) -> &RequestOptions;
34
35    /// Add headers to RequestOptions
36    fn headers(mut self, headers: HeaderMap) -> Self {
37        self.options_mut().with_headers(headers);
38        self
39    }
40
41    /// Add a single header to RequestOptions
42    fn header<K, V>(mut self, key: K, value: V) -> Result<Self, OpenAIError>
43    where
44        K: reqwest::header::IntoHeaderName,
45        V: TryInto<reqwest::header::HeaderValue>,
46        V::Error: Into<reqwest::header::InvalidHeaderValue>,
47    {
48        self.options_mut().with_header(key, value)?;
49        Ok(self)
50    }
51
52    /// Add query parameters to RequestOptions
53    fn query<Q: Serialize + ?Sized>(mut self, query: &Q) -> Result<Self, OpenAIError> {
54        self.options_mut().with_query(query)?;
55        Ok(self)
56    }
57
58    /// Add a path to RequestOptions
59    fn path<P: Into<String>>(mut self, path: P) -> Result<Self, OpenAIError> {
60        self.options_mut().with_path(path.into().as_str())?;
61        Ok(self)
62    }
63}