async_llm/providers/
config.rs

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
use derive_builder::Builder;
use reqwest::header::{HeaderMap, HeaderValue, AUTHORIZATION, CONTENT_TYPE};
use secrecy::{ExposeSecret, SecretString};
use std::fmt::Debug;

use crate::error::Error;

use super::openai::OPENAI_BASE_URL;

pub const OPENAI_ORGANIZATION: &str = "OpenAI-Organization";
pub const OPENAI_PROJECT: &str = "OpenAI-Project";
pub const OPENAI_BETA: &str = "OpenAI-Beta";

pub trait Config: Debug + Clone + Send + Sync {
    fn headers(&self) -> Result<HeaderMap, Error>;
    fn url(&self, path: &str) -> String;
    fn query(&self) -> Vec<(&str, &str)>;

    fn base_url(&self) -> &str;

    fn api_key(&self) -> Option<&SecretString>;

    fn stream_done_message(&self) -> &'static str {
        "[DONE]"
    }
}

#[derive(Debug, Clone, Builder)]
#[builder(derive(Debug))]
#[builder(build_fn(error = Error))]
pub struct OpenAIConfig {
    pub(crate) base_url: String,
    pub(crate) api_key: Option<SecretString>,
    pub(crate) org_id: Option<String>,
    pub(crate) project_id: Option<String>,
    pub(crate) beta: Option<String>,
}

fn sanitize_base_url(input: impl Into<String>) -> String {
    let input: String = input.into();
    input.trim_end_matches(|c| c == '/' || c == ' ').to_string()
}

impl OpenAIConfig {
    pub fn new(base_url: impl Into<String>, api_key: Option<SecretString>) -> Self {
        Self {
            base_url: sanitize_base_url(base_url),
            api_key: api_key.into(),
            beta: Some("assistants=v2".into()),
            ..Default::default()
        }
    }
}

impl Default for OpenAIConfig {
    fn default() -> Self {
        Self {
            base_url: sanitize_base_url(
                std::env::var("OPENAI_BASE_URL").unwrap_or_else(|_| OPENAI_BASE_URL.to_string()),
            ),
            api_key: std::env::var("OPENAI_API_KEY").map(|v| v.into()).ok(),
            org_id: Default::default(),
            project_id: Default::default(),
            beta: Some("assistants=v2".into()),
        }
    }
}

impl Config for OpenAIConfig {
    fn headers(&self) -> Result<reqwest::header::HeaderMap, Error> {
        let mut headers = HeaderMap::new();

        headers.insert(CONTENT_TYPE, HeaderValue::from_static("application/json"));

        if let Some(api_key) = &self.api_key {
            let bearer = format!("Bearer {}", api_key.expose_secret());
            headers.insert(
                AUTHORIZATION,
                bearer.parse().map_err(|e| {
                    Error::InvalidConfig(format!(
                        "Failed to convert api key id to header value. {:?}",
                        e
                    ))
                })?,
            );
        }

        if let Some(org_id) = &self.org_id {
            headers.insert(
                OPENAI_ORGANIZATION,
                org_id.parse().map_err(|e| {
                    Error::InvalidConfig(format!(
                        "Failed to convert organization id to header value. {:?}",
                        e
                    ))
                })?,
            );
        }
        if let Some(project_id) = &self.project_id {
            headers.insert(
                OPENAI_PROJECT,
                project_id.parse().map_err(|e| {
                    Error::InvalidConfig(format!(
                        "Failed to convert project id to header value. {:?}",
                        e
                    ))
                })?,
            );
        }

        // See: https://github.com/64bit/async-openai/blob/bd7a87e335630d5d2f3e6cef30d15633048937b3/async-openai/src/config.rs#L111
        if let Some(beta) = &self.beta {
            headers.insert(
                OPENAI_BETA,
                beta.parse().map_err(|e| {
                    Error::InvalidConfig(format!("Failed to convert beta to header. {:?}", e))
                })?,
            );
        }
        Ok(headers)
    }

    fn url(&self, path: &str) -> String {
        format!("{}{}", self.base_url, path)
    }

    fn query(&self) -> Vec<(&str, &str)> {
        vec![]
    }

    fn base_url(&self) -> &str {
        &self.base_url
    }

    fn api_key(&self) -> Option<&SecretString> {
        self.api_key.as_ref()
    }
}