1use std::io::Read;
2use std::{fs::File, path::PathBuf};
3
4use openai_api_rs::v1::api::OpenAIClient;
5use openai_api_rs::v1::chat_completion;
6use openai_api_rs::v1::chat_completion::chat_completion::ChatCompletionRequest;
7
8use crate::config::Config;
9
10pub fn read_template(template_file: &PathBuf) -> std::io::Result<String> {
11 let file = File::open(template_file)?;
12 let mut reader = std::io::BufReader::new(file);
13 let mut contents = String::new();
14
15 reader.read_to_string(&mut contents)?;
16
17 Ok(contents)
18}
19
20pub async fn generate_commit(
21 content: String,
22 config: Config,
23) -> Result<String, Box<dyn std::error::Error>> {
24 let system_message = "You are a commit message generator. I will provide you with a git diff, and I would like you to generate an appropriate commit message using the conventional commit format. Do not write any explanations or other words, just reply with the commit message.";
25 let client = OpenAIClient::builder()
26 .with_endpoint(config.openai_api_url)
27 .with_api_key(config.openai_api_key)
28 .build()?;
29
30 let req = ChatCompletionRequest::new(
31 config.model_name,
32 vec![
33 chat_completion::ChatCompletionMessage {
34 role: chat_completion::MessageRole::system,
35 content: chat_completion::Content::Text(system_message.to_string()),
36 name: None,
37 tool_calls: None,
38 tool_call_id: None,
39 },
40 chat_completion::ChatCompletionMessage {
41 role: chat_completion::MessageRole::user,
42 content: chat_completion::Content::Text(content),
43 name: None,
44 tool_calls: None,
45 tool_call_id: None,
46 },
47 ],
48 );
49
50 let result = client.chat_completion(req).await?;
51 let contents = &result.inner.choices[0].message.content;
52
53 match contents {
54 Some(content) => Ok(content.clone()),
55 None => Ok(String::from("")),
56 }
57}