Skip to main content

langchain_rust/llm/openai/
mod.rs

1use std::pin::Pin;
2
3pub use async_openai::config::{AzureConfig, Config, OpenAIConfig};
4
5use async_openai::types::chat::{
6    ChatChoiceStream, ChatCompletionMessageToolCalls, ChatCompletionRequestAssistantMessageArgs,
7    ChatCompletionRequestMessage, ChatCompletionRequestMessageContentPartImageArgs,
8    ChatCompletionRequestSystemMessageArgs, ChatCompletionRequestToolMessageArgs,
9    ChatCompletionRequestUserMessageArgs, ChatCompletionRequestUserMessageContent,
10    ChatCompletionRequestUserMessageContentPart, ChatCompletionStreamOptions,
11    ChatCompletionToolChoiceOption, ChatCompletionTools, CreateChatCompletionRequest,
12    CreateChatCompletionRequestArgs, ResponseFormat, StopConfiguration,
13};
14use async_openai::{error::OpenAIError, Client};
15use async_trait::async_trait;
16use futures::{Stream, StreamExt};
17
18use crate::schemas::convert::{LangchainIntoOpenAI, TryLangchainIntoOpenAI};
19use crate::{
20    language_models::{llm::LLM, options::CallOptions, GenerateResult, LLMError, TokenUsage},
21    schemas::{
22        messages::{Message, MessageType},
23        StreamData,
24    },
25};
26
27#[derive(Clone)]
28pub enum OpenAIModel {
29    Gpt35,
30    Gpt4,
31    Gpt4Turbo,
32    Gpt4o,
33    Gpt4oMini,
34}
35
36impl ToString for OpenAIModel {
37    fn to_string(&self) -> String {
38        match self {
39            OpenAIModel::Gpt35 => "gpt-3.5-turbo".to_string(),
40            OpenAIModel::Gpt4 => "gpt-4".to_string(),
41            OpenAIModel::Gpt4Turbo => "gpt-4-turbo-preview".to_string(),
42            OpenAIModel::Gpt4o => "gpt-4o".to_string(),
43            OpenAIModel::Gpt4oMini => "gpt-4o-mini".to_string(),
44        }
45    }
46}
47
48impl Into<String> for OpenAIModel {
49    fn into(self) -> String {
50        self.to_string()
51    }
52}
53
54#[derive(Clone)]
55pub struct OpenAI<C: Config> {
56    config: C,
57    options: CallOptions,
58    model: String,
59}
60
61impl<C: Config> OpenAI<C> {
62    pub fn new(config: C) -> Self {
63        Self {
64            config,
65            options: CallOptions::default(),
66            model: OpenAIModel::Gpt4oMini.to_string(),
67        }
68    }
69
70    pub fn with_model<S: Into<String>>(mut self, model: S) -> Self {
71        self.model = model.into();
72        self
73    }
74
75    pub fn with_config(mut self, config: C) -> Self {
76        self.config = config;
77        self
78    }
79
80    pub fn with_options(mut self, options: CallOptions) -> Self {
81        self.options = options;
82        self
83    }
84}
85
86impl Default for OpenAI<OpenAIConfig> {
87    fn default() -> Self {
88        Self::new(OpenAIConfig::default())
89    }
90}
91
92#[async_trait]
93impl<C: Config + Clone + Send + Sync + 'static> LLM for OpenAI<C> {
94    async fn generate(&self, prompt: &[Message]) -> Result<GenerateResult, LLMError> {
95        let client = Client::with_config(self.config.clone());
96        let request = self.generate_request(prompt, self.options.streaming_func.is_some())?;
97        match &self.options.streaming_func {
98            Some(func) => {
99                let mut stream = client.chat().create_stream(request).await?;
100                let mut generate_result = GenerateResult::default();
101                while let Some(result) = stream.next().await {
102                    match result {
103                        Ok(response) => {
104                            if let Some(usage) = response.usage {
105                                generate_result.tokens = Some(TokenUsage {
106                                    prompt_tokens: usage.prompt_tokens,
107                                    completion_tokens: usage.completion_tokens,
108                                    total_tokens: usage.total_tokens,
109                                });
110                            }
111                            for chat_choice in response.choices.iter() {
112                                let chat_choice: ChatChoiceStream = chat_choice.clone();
113                                {
114                                    let mut func = func.lock().await;
115                                    let _ = func(
116                                        serde_json::to_string(&chat_choice).unwrap_or("".into()),
117                                    )
118                                    .await;
119                                }
120                                if let Some(content) = chat_choice.delta.content {
121                                    generate_result.generation.push_str(&content);
122                                }
123                            }
124                        }
125                        Err(err) => {
126                            eprintln!("Error from streaming response: {:?}", err);
127                        }
128                    }
129                }
130                Ok(generate_result)
131            }
132            None => {
133                let response = client.chat().create(request).await?;
134                let mut generate_result = GenerateResult::default();
135
136                if let Some(usage) = response.usage {
137                    generate_result.tokens = Some(TokenUsage {
138                        prompt_tokens: usage.prompt_tokens,
139                        completion_tokens: usage.completion_tokens,
140                        total_tokens: usage.total_tokens,
141                    });
142                }
143
144                if let Some(choice) = &response.choices.first() {
145                    generate_result.generation = choice.message.content.clone().unwrap_or_default();
146                    if let Some(function) = &choice.message.tool_calls {
147                        generate_result.generation =
148                            serde_json::to_string(&function).unwrap_or_default();
149                    }
150                } else {
151                    generate_result.generation = "".to_string();
152                }
153
154                Ok(generate_result)
155            }
156        }
157    }
158
159    async fn invoke(&self, prompt: &str) -> Result<String, LLMError> {
160        self.generate(&[Message::new_human_message(prompt)])
161            .await
162            .map(|res| res.generation)
163    }
164
165    async fn stream(
166        &self,
167        messages: &[Message],
168    ) -> Result<Pin<Box<dyn Stream<Item = Result<StreamData, LLMError>> + Send>>, LLMError> {
169        let client = Client::with_config(self.config.clone());
170        let request = self.generate_request(messages, true)?;
171
172        let original_stream = client.chat().create_stream(request).await?;
173
174        let new_stream = original_stream.map(|result| match result {
175            Ok(completion) => {
176                let value_completion = serde_json::to_value(completion).map_err(LLMError::from)?;
177                let usage = value_completion.pointer("/usage");
178                if usage.is_some() && !usage.unwrap().is_null() {
179                    let usage = serde_json::from_value::<TokenUsage>(usage.unwrap().clone())
180                        .map_err(LLMError::from)?;
181                    return Ok(StreamData::new(value_completion, Some(usage), ""));
182                }
183                let content = value_completion
184                    .pointer("/choices/0/delta/content")
185                    .ok_or(LLMError::ContentNotFound(
186                        "/choices/0/delta/content".to_string(),
187                    ))?
188                    .clone();
189
190                Ok(StreamData::new(
191                    value_completion,
192                    None,
193                    content.as_str().unwrap_or(""),
194                ))
195            }
196            Err(e) => Err(LLMError::from(e)),
197        });
198
199        Ok(Box::pin(new_stream))
200    }
201
202    fn add_options(&mut self, options: CallOptions) {
203        self.options.merge_options(options)
204    }
205}
206
207impl<C: Config> OpenAI<C> {
208    fn to_openai_messages(
209        &self,
210        messages: &[Message],
211    ) -> Result<Vec<ChatCompletionRequestMessage>, LLMError> {
212        let mut openai_messages: Vec<ChatCompletionRequestMessage> = Vec::new();
213        for m in messages {
214            match m.message_type {
215                MessageType::AIMessage => openai_messages.push(match &m.tool_calls {
216                    Some(value) => {
217                        let function: Vec<ChatCompletionMessageToolCalls> =
218                            serde_json::from_value(value.clone())?;
219                        ChatCompletionRequestAssistantMessageArgs::default()
220                            .tool_calls(function)
221                            .content(m.content.clone())
222                            .build()?
223                            .into()
224                    }
225                    None => ChatCompletionRequestAssistantMessageArgs::default()
226                        .content(m.content.clone())
227                        .build()?
228                        .into(),
229                }),
230                MessageType::HumanMessage => {
231                    let content: ChatCompletionRequestUserMessageContent = match m.images.clone() {
232                        Some(images) => {
233                            let content: Result<
234                                Vec<ChatCompletionRequestUserMessageContentPart>,
235                                OpenAIError,
236                            > = images
237                                .into_iter()
238                                .map(|image| {
239                                    Ok(ChatCompletionRequestMessageContentPartImageArgs::default()
240                                        .image_url(image.image_url)
241                                        .build()?
242                                        .into())
243                                })
244                                .collect();
245
246                            content?.into()
247                        }
248                        None => m.content.clone().into(),
249                    };
250
251                    openai_messages.push(
252                        ChatCompletionRequestUserMessageArgs::default()
253                            .content(content)
254                            .build()?
255                            .into(),
256                    )
257                }
258                MessageType::SystemMessage => openai_messages.push(
259                    ChatCompletionRequestSystemMessageArgs::default()
260                        .content(m.content.clone())
261                        .build()?
262                        .into(),
263                ),
264                MessageType::ToolMessage => {
265                    openai_messages.push(
266                        ChatCompletionRequestToolMessageArgs::default()
267                            .content(m.content.clone())
268                            .tool_call_id(m.id.clone().unwrap_or_default())
269                            .build()?
270                            .into(),
271                    );
272                }
273            }
274        }
275        Ok(openai_messages)
276    }
277
278    fn generate_request(
279        &self,
280        messages: &[Message],
281        stream: bool,
282    ) -> Result<CreateChatCompletionRequest, LLMError> {
283        let messages: Vec<ChatCompletionRequestMessage> = self.to_openai_messages(messages)?;
284        let mut request_builder = CreateChatCompletionRequestArgs::default();
285        if let Some(temperature) = self.options.temperature {
286            request_builder.temperature(temperature);
287        }
288        if let Some(max_tokens) = self.options.max_tokens {
289            request_builder.max_tokens(max_tokens);
290        }
291        if stream {
292            if let Some(include_usage) = self.options.stream_usage {
293                request_builder.stream_options(ChatCompletionStreamOptions {
294                    include_usage: Some(include_usage),
295                    include_obfuscation: None,
296                });
297            }
298        }
299        request_builder.model(self.model.to_string());
300        if let Some(stop_words) = &self.options.stop_words {
301            request_builder.stop(StopConfiguration::StringArray(stop_words.clone()));
302        }
303
304        if let Some(functions) = &self.options.functions {
305            let functions: Result<Vec<ChatCompletionTools>, OpenAIError> = functions
306                .clone()
307                .into_iter()
308                .map(|f| f.try_into_openai())
309                .collect();
310            request_builder.tools(functions?);
311        }
312
313        if let Some(behavior) = &self.options.function_call_behavior {
314            request_builder
315                .tool_choice::<ChatCompletionToolChoiceOption>(behavior.clone().into_openai());
316        }
317
318        if let Some(response_format) = &self.options.response_format {
319            request_builder
320                .response_format::<ResponseFormat>(response_format.clone().into_openai());
321        }
322
323        request_builder.messages(messages);
324        Ok(request_builder.build()?)
325    }
326}
327
328#[cfg(test)]
329mod mock_tests;
330
331#[cfg(test)]
332mod tests {
333    use crate::schemas::FunctionDefinition;
334
335    use super::*;
336
337    use base64::prelude::*;
338    use serde_json::json;
339    use std::sync::Arc;
340    use tokio::sync::Mutex;
341    use tokio::test;
342
343    #[test]
344    #[ignore]
345    async fn test_invoke() {
346        let message_complete = Arc::new(Mutex::new(String::new()));
347
348        // Define the streaming function
349        // This function will append the content received from the stream to `message_complete`
350        let streaming_func = {
351            let message_complete = message_complete.clone();
352            move |content: String| {
353                let message_complete = message_complete.clone();
354                async move {
355                    let mut message_complete_lock = message_complete.lock().await;
356                    println!("Content: {:?}", content);
357                    message_complete_lock.push_str(&content);
358                    Ok(())
359                }
360            }
361        };
362        let options = CallOptions::new().with_streaming_func(streaming_func);
363        // Setup the OpenAI client with the necessary options
364        let open_ai = OpenAI::new(OpenAIConfig::default())
365            .with_model(OpenAIModel::Gpt35.to_string()) // You can change the model as needed
366            .with_options(options);
367
368        // Define a set of messages to send to the generate function
369
370        // Call the generate function
371        match open_ai.invoke("hola").await {
372            Ok(result) => {
373                // Print the response from the generate function
374                println!("Generate Result: {:?}", result);
375                println!("Message Complete: {:?}", message_complete.lock().await);
376            }
377            Err(e) => {
378                // Handle any errors
379                eprintln!("Error calling generate: {:?}", e);
380            }
381        }
382    }
383
384    #[test]
385    #[ignore]
386    async fn test_generate_function() {
387        let message_complete = Arc::new(Mutex::new(String::new()));
388
389        // Define the streaming function
390        // This function will append the content received from the stream to `message_complete`
391        let streaming_func = {
392            let message_complete = message_complete.clone();
393            move |content: String| {
394                let message_complete = message_complete.clone();
395                async move {
396                    let content = serde_json::from_str::<ChatChoiceStream>(&content).unwrap();
397                    if content.finish_reason.is_some() {
398                        return Ok(());
399                    }
400                    let mut message_complete_lock = message_complete.lock().await;
401                    println!("Content: {:?}", content);
402                    message_complete_lock.push_str(&content.delta.content.unwrap());
403                    Ok(())
404                }
405            }
406        };
407        // Define the streaming function as an async block without capturing external references directly
408        let options = CallOptions::new().with_streaming_func(streaming_func);
409        // Setup the OpenAI client with the necessary options
410        let open_ai = OpenAI::new(OpenAIConfig::default())
411            .with_model(OpenAIModel::Gpt35.to_string()) // You can change the model as needed
412            .with_options(options);
413
414        // Define a set of messages to send to the generate function
415        let messages = vec![Message::new_human_message("Hello, how are you?")];
416
417        // Call the generate function
418        match open_ai.generate(&messages).await {
419            Ok(result) => {
420                // Print the response from the generate function
421                println!("Generate Result: {:?}", result);
422                println!("Message Complete: {:?}", message_complete.lock().await);
423            }
424            Err(e) => {
425                // Handle any errors
426                eprintln!("Error calling generate: {:?}", e);
427            }
428        }
429    }
430
431    #[test]
432    #[ignore]
433    async fn test_openai_stream() {
434        // Setup the OpenAI client with the necessary options
435        let open_ai = OpenAI::default().with_model(OpenAIModel::Gpt35.to_string());
436
437        // Define a set of messages to send to the generate function
438        let messages = vec![Message::new_human_message("Hello, how are you?")];
439
440        open_ai
441            .stream(&messages)
442            .await
443            .unwrap()
444            .for_each(|result| async {
445                match result {
446                    Ok(stream_data) => {
447                        println!("Stream Data: {:?}", stream_data.content);
448                    }
449                    Err(e) => {
450                        eprintln!("Error calling generate: {:?}", e);
451                    }
452                }
453            })
454            .await;
455    }
456
457    #[test]
458    #[ignore]
459    async fn test_function() {
460        let mut functions = Vec::new();
461        functions.push(FunctionDefinition {
462            name: "cli".to_string(),
463            description: "Use the Ubuntu command line to preform any action you wish.".to_string(),
464            parameters: json!({
465                "type": "object",
466                "properties": {
467                    "command": {
468                        "type": "string",
469                        "description": "The raw command you want executed"
470                    }
471                },
472                "required": ["command"]
473            }),
474        });
475
476        let llm = OpenAI::default()
477            .with_model(OpenAIModel::Gpt35)
478            .with_config(OpenAIConfig::new())
479            .with_options(CallOptions::new().with_functions(functions));
480        let response = llm
481            .invoke("Use the command line to create a new rust project. Execute the first command.")
482            .await
483            .unwrap();
484        println!("{}", response)
485    }
486
487    #[test]
488    #[ignore]
489    async fn test_generate_with_image_message() {
490        // Setup the OpenAI client with the necessary options
491        let open_ai =
492            OpenAI::new(OpenAIConfig::default()).with_model(OpenAIModel::Gpt4o.to_string());
493
494        // Convert image to base64
495        let image = std::fs::read("./src/llm/test_data/example.jpg").unwrap();
496        let image_base64 = BASE64_STANDARD.encode(image);
497
498        // Define a set of messages to send to the generate function
499        let image_urls = vec![format!("data:image/jpeg;base64,{image_base64}")];
500        let messages = vec![
501            Message::new_human_message("Describe this image"),
502            Message::new_human_message_with_images(image_urls),
503        ];
504
505        // Call the generate function
506        let response = open_ai.generate(&messages).await.unwrap();
507        println!("Response: {:?}", response);
508    }
509}