bridge_common/clients/
openai.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
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
// Copyright 2024 StarfleetAI
// SPDX-License-Identifier: Apache-2.0

use std::{collections::HashMap, ops::Deref};

use anyhow::Context;
use reqwest::Response;
use serde::{Deserialize, Serialize};
use serde_json::Value;
use tracing::debug;

use crate::types::Result;

pub struct Client {
    pub api_key: String,
    pub api_url: String,
    pub user_agent: String,
}

#[derive(Debug, Serialize, Deserialize, Clone)]
#[serde(tag = "role")]
pub enum Message {
    #[serde(rename = "system")]
    System {
        content: String,
        #[serde(skip_serializing_if = "Option::is_none")]
        name: Option<String>,
    },
    #[serde(rename = "user")]
    User {
        content: String,
        #[serde(skip_serializing_if = "Option::is_none")]
        name: Option<String>,
    },
    #[serde(rename = "assistant")]
    Assistant {
        #[serde(skip_serializing_if = "Option::is_none")]
        content: Option<String>,
        #[serde(skip_serializing_if = "Option::is_none")]
        name: Option<String>,
        #[serde(skip_serializing_if = "Option::is_none")]
        tool_calls: Option<Value>,
    },
    #[serde(rename = "tool")]
    Tool {
        content: String,
        tool_call_id: String,
    },
}

impl Message {
    #[must_use]
    pub fn tool_calls(&self) -> ToolCalls {
        match self {
            Message::Assistant { tool_calls, .. } => match tool_calls {
                Some(tool_calls) => match serde_json::from_value(tool_calls.clone()) {
                    Ok(tool_calls) => tool_calls,
                    Err(_) => ToolCalls::default(),
                },
                None => ToolCalls::default(),
            },
            _ => ToolCalls::default(),
        }
    }
}

impl TryFrom<crate::types::messages::Message> for Message {
    type Error = anyhow::Error;

    fn try_from(
        message: crate::types::messages::Message,
    ) -> std::result::Result<Self, Self::Error> {
        Ok(match message.role {
            crate::types::messages::Role::System => Message::System {
                content: message
                    .content
                    .with_context(|| "Failed to get message content")?,
                name: None,
            },
            crate::types::messages::Role::User => Message::User {
                content: message
                    .content
                    .with_context(|| "Failed to get message content")?,
                name: None,
            },
            crate::types::messages::Role::CodeInterpreter => Message::User {
                content: message
                    .content
                    .with_context(|| "Failed to get message content")?,
                name: Some("Code-Interpreter".to_string()),
            },
            crate::types::messages::Role::Assistant => Message::Assistant {
                content: message.content,
                name: None,
                tool_calls: message.tool_calls,
            },
            crate::types::messages::Role::Tool => Message::Tool {
                content: message
                    .content
                    .with_context(|| "Failed to get message content")?,
                tool_call_id: message
                    .tool_call_id
                    .with_context(|| "Failed to get tool call id")?,
            },
        })
    }
}

#[derive(Serialize, Deserialize, Default, Clone, Debug)]
pub struct ToolCalls(pub Vec<ToolCall>);

impl Deref for ToolCalls {
    type Target = Vec<ToolCall>;

    fn deref(&self) -> &Self::Target {
        &self.0
    }
}

#[derive(Debug, Serialize, Deserialize, Clone)]
pub struct ToolCall {
    pub id: String,
    #[serde(rename = "type")]
    pub type_: ToolType,
    pub function: FunctionCall,
}

#[derive(Debug, Serialize, Deserialize, Clone)]
pub enum ToolType {
    #[serde(rename = "function")]
    Function,
}

#[derive(Debug, Serialize, Deserialize, Clone)]
pub struct FunctionCall {
    pub name: String,
    pub arguments: String,
}

#[derive(Serialize, Deserialize, Debug, Clone)]
pub struct Tool {
    #[serde(rename = "type")]
    pub type_: String,
    pub function: Function,
}

#[derive(Serialize, Deserialize, Debug, Clone, Default)]
pub struct Function {
    pub name: String,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub description: Option<String>,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub parameters: Option<FunctionParameters>,
}

#[derive(Serialize, Deserialize, Debug, Clone)]
pub struct FunctionParameters {
    #[serde(rename = "type")]
    pub type_: String,
    pub properties: HashMap<String, FunctionPropertyValue>,
}

#[derive(Serialize, Deserialize, Debug, Clone)]
pub struct FunctionPropertyValue {
    #[serde(rename = "type")]
    pub type_: String,
    pub description: String,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub items: Option<FunctionParameters>,
}

#[derive(Debug, Serialize, Default)]
pub struct CreateChatCompletionRequest<'a> {
    pub model: &'a str,
    pub messages: Vec<Message>,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub tools: Option<Vec<Tool>>,
    pub stream: bool,
}

#[derive(Debug, Deserialize)]
pub struct ChatCompletionChunk {
    pub id: String,
    pub object: String,
    pub created: u32,
    pub model: String,
    pub system_fingerprint: Option<String>,
    pub choices: Vec<ChunkChoice>,
}

#[derive(Debug, Deserialize)]
pub struct ChunkChoice {
    pub index: u32,
    pub delta: Message,
    pub finish_reason: Option<String>,
    pub logprobs: Option<f32>,
}

#[derive(Debug, Deserialize)]
pub struct ChatCompletion {
    pub created: u32,
    pub id: String,
    pub model: String,
    pub object: String,
    pub choices: Vec<Choice>,
    pub usage: Usage,
}

#[derive(Debug, Deserialize)]
pub struct Choice {
    pub finish_reason: String,
    pub index: u32,
    pub message: Message,
    pub logprobs: Option<f32>,
}

#[derive(Debug, Deserialize)]
pub struct Usage {
    pub completion_tokens: u32,
    pub prompt_tokens: u32,
    pub total_tokens: u32,
}

impl<'a> Client {
    #[must_use]
    pub fn new(api_key: &'a str, api_url: &'a str, user_agent: &'a str) -> Self {
        Self {
            api_key: api_key.to_string(),
            api_url: api_url.to_string(),
            user_agent: user_agent.to_string(),
        }
    }

    /// Creates a streaming chat completion.
    ///
    /// # Errors
    ///
    /// Returns error if there was a problem while making the API call.
    pub async fn create_chat_completion_stream(
        &self,
        mut request: CreateChatCompletionRequest<'_>,
    ) -> Result<Response> {
        request.stream = true;

        self.post_stream("chat/completions", &request).await
    }

    /// Creates a chat completion.
    ///
    /// # Errors
    ///
    /// Returns error if there was a problem while making the API call.
    pub async fn create_chat_completion(
        &self,
        request: CreateChatCompletionRequest<'_>,
    ) -> Result<ChatCompletion> {
        self.post("chat/completions", &request).await
    }

    /// Sends a stream POST request, returns the response for further processing.
    ///
    /// # Errors
    ///
    /// Returns error if there was a problem while sending the request or
    /// deserializing the response.
    pub async fn post_stream<B>(&self, endpoint: &str, body: B) -> Result<Response>
    where
        B: serde::Serialize,
    {
        let url = format!("{}{endpoint}", self.api_url);
        let client = reqwest::Client::new();

        let body =
            serde_json::to_value(body).with_context(|| "Failed to serialize request body")?;

        debug!("Inference API request: {:?}", body.to_string());

        Ok(client
            .post(&url)
            .header("Authorization", format!("Bearer {}", self.api_key))
            .header("Content-Type", "application/json")
            .header("User-Agent", self.user_agent.clone())
            .json(&body)
            .send()
            .await
            .with_context(|| "Failed to send request")?)
    }

    /// Sends a POST request, deserializes the response to the given type.
    ///
    /// # Errors
    ///
    /// Returns error if there was a problem while sending the request or
    /// deserializing the response.
    pub async fn post<T, B>(&self, endpoint: &str, body: B) -> Result<T>
    where
        T: serde::de::DeserializeOwned,
        B: serde::Serialize,
    {
        let url = format!("{}{endpoint}", self.api_url);
        let client = reqwest::Client::new();

        let body =
            serde_json::to_value(body).with_context(|| "Failed to serialize request body")?;
        debug!("Inference API request: {:?}", body.to_string());

        let response = client
            .post(&url)
            .header("Authorization", format!("Bearer {}", self.api_key))
            .header("Content-Type", "application/json")
            .header("User-Agent", self.user_agent.clone())
            .json(&body)
            .send()
            .await
            .with_context(|| "Failed to send request")?
            .text()
            .await
            .with_context(|| "Failed to get response text")?;

        debug!("Inference API response: {:?}", response);

        Ok(serde_json::from_str(&response)?)
    }
}