Skip to main content

async_openai/
traits.rs

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