use serde::{Deserialize, Serialize};
use std::time::Duration;
#[derive(Clone, Debug, Serialize, Deserialize)]
pub struct OpenAIConfig {
api_key: String,
model: String,
#[serde(default = "default_base_url")]
base_url: String,
#[serde(skip_serializing_if = "Option::is_none")]
organization: Option<String>,
#[serde(with = "humantime_serde", default = "default_timeout")]
timeout: Duration,
#[serde(default = "default_max_tokens")]
max_tokens: usize,
#[serde(default = "default_temperature")]
temperature: f32,
#[serde(default)]
json_mode: bool,
#[serde(default)]
stream: bool,
}
fn default_base_url() -> String {
"https://api.openai.com/v1".to_string()
}
fn default_timeout() -> Duration {
Duration::from_secs(30)
}
fn default_max_tokens() -> usize {
1024
}
fn default_temperature() -> f32 {
0.7
}
impl OpenAIConfig {
pub fn new() -> Self {
Self {
api_key: String::new(),
model: "gpt-4".to_string(),
base_url: default_base_url(),
organization: None,
timeout: default_timeout(),
max_tokens: default_max_tokens(),
temperature: default_temperature(),
json_mode: false,
stream: false,
}
}
pub fn with_api_key(mut self, api_key: impl Into<String>) -> Self {
self.api_key = api_key.into();
self
}
pub fn with_model(mut self, model: impl Into<String>) -> Self {
self.model = model.into();
self
}
pub fn with_base_url(mut self, base_url: impl Into<String>) -> Self {
self.base_url = base_url.into();
self
}
pub fn with_organization(mut self, organization: impl Into<String>) -> Self {
self.organization = Some(organization.into());
self
}
pub fn with_timeout(mut self, timeout: Duration) -> Self {
self.timeout = timeout;
self
}
pub fn with_max_tokens(mut self, max_tokens: usize) -> Self {
self.max_tokens = max_tokens;
self
}
pub fn with_temperature(mut self, temperature: f32) -> Self {
self.temperature = temperature;
self
}
pub fn with_json_mode(mut self, enabled: bool) -> Self {
self.json_mode = enabled;
self
}
pub fn with_stream(mut self, enabled: bool) -> Self {
self.stream = enabled;
self
}
pub fn api_key(&self) -> &str {
&self.api_key
}
pub fn model(&self) -> &str {
&self.model
}
pub fn base_url(&self) -> &str {
&self.base_url
}
pub fn organization(&self) -> Option<&str> {
self.organization.as_deref()
}
pub fn timeout(&self) -> Duration {
self.timeout
}
pub fn max_tokens(&self) -> usize {
self.max_tokens
}
pub fn temperature(&self) -> f32 {
self.temperature
}
pub fn json_mode(&self) -> bool {
self.json_mode
}
pub fn stream(&self) -> bool {
self.stream
}
}
impl Default for OpenAIConfig {
fn default() -> Self {
Self::new()
}
}