Skip to content

Commit

Permalink
Merge pull request #86 from takanotume24/feature/44__fix_the_position…
Browse files Browse the repository at this point in the history
…_of_the_session_list

Feature/44  fix the position of the session list
  • Loading branch information
takanotume24 authored Dec 3, 2024
2 parents b7b472a + 1b684c6 commit 1d46b68
Show file tree
Hide file tree
Showing 24 changed files with 476 additions and 314 deletions.
7 changes: 7 additions & 0 deletions package-lock.json

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

1 change: 1 addition & 0 deletions package.json
Original file line number Diff line number Diff line change
Expand Up @@ -13,6 +13,7 @@
"@tauri-apps/api": "^2",
"@tauri-apps/plugin-shell": "^2",
"bootstrap": "^5.3.3",
"dayjs": "^1.11.13",
"marked": "^15.0.3",
"uuid": "^11.0.3",
"vue": "^3.5.13"
Expand Down
18 changes: 18 additions & 0 deletions src-tauri/src/app_type.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,18 @@
use serde::Serialize;

#[derive(Serialize)]
pub struct ChatResponse {
pub response: String,
pub created_at: String,
}

#[derive(Serialize)]
pub struct RawDatabaseChatEntry {
pub session_id: String,
pub question: String,
pub answer: String,
pub created_at: String,
}

#[derive(Serialize)]
pub struct SessionId(pub String);
48 changes: 26 additions & 22 deletions src-tauri/src/get_chat_history.rs
Original file line number Diff line number Diff line change
Expand Up @@ -3,33 +3,37 @@ use crate::get_db_connection::get_db_connection;
use crate::models::ChatHistory;
use crate::schema::chat_history::dsl::*;
use diesel::prelude::*;
use std::collections::HashMap;
use tauri::State;
use crate::app_type::RawDatabaseChatEntry;
use tauri::async_runtime::block_on;

#[tauri::command]
pub async fn get_chat_history(
pub fn get_chat_history(
db: State<'_, Database>,
) -> Result<Vec<HashMap<String, String>>, String> {
// Use the helper function to get a mutable connection
let mut conn = get_db_connection(&db)?;
) -> Result<Vec<RawDatabaseChatEntry>, String> {
// Use block_on to run the async code synchronously
block_on(async {
// Use the helper function to get a mutable connection
let mut conn = get_db_connection(&db)?;

// Pass the mutable reference to Diesel operations
let results = chat_history
.load::<ChatHistory>(&mut conn)
.map_err(|e| e.to_string())?;
// Pass the mutable reference to Diesel operations
let results = chat_history
.load::<ChatHistory>(&mut conn)
.map_err(|e| e.to_string())?;

// Transform results into a vector of hash maps using functional style
let rows: Vec<_> = results
.into_iter()
.map(|chat| {
let mut map = HashMap::new();
map.insert("session_id".to_string(), chat.session_id.clone());
map.insert("question".to_string(), chat.question.clone());
map.insert("answer".to_string(), chat.answer.clone());
map.insert("created_at".to_string(), chat.created_at.to_string());
map
})
.collect();
// Transform results into a vector of hash maps using functional style
let rows: Vec<RawDatabaseChatEntry> = results
.into_iter()
.map(|chat| {
RawDatabaseChatEntry {
session_id: chat.session_id.clone(),
question: chat.question.clone(),
answer: chat.answer.clone(),
created_at: chat.created_at.to_string(),
}
})
.collect();

Ok(rows)
Ok(rows)
})
}
39 changes: 39 additions & 0 deletions src-tauri/src/get_chat_history_by_session.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,39 @@
use crate::database::Database;
use crate::get_db_connection::get_db_connection;
use crate::models::ChatHistory;
use crate::schema::chat_history::dsl::*;
use diesel::prelude::*;
use tauri::State;
use crate::app_type::RawDatabaseChatEntry;
use tauri::async_runtime::block_on;

#[tauri::command]
pub fn get_chat_history_by_session(
db: State<'_, Database>,
target_session_id: String,
) -> Result<Vec<RawDatabaseChatEntry>, String> {
// Use block_on to run the async code synchronously
block_on(async {
// Use the helper function to get a mutable connection
let mut conn = get_db_connection(&db)?;

// Filter the chat history by the specific session_id
let results = chat_history
.filter(session_id.eq(target_session_id))
.load::<ChatHistory>(&mut conn)
.map_err(|e| e.to_string())?;

// Transform results into a vector of RawDatabaseChatEntry
let rows: Vec<RawDatabaseChatEntry> = results
.into_iter()
.map(|chat| RawDatabaseChatEntry {
session_id: chat.session_id.clone(),
question: chat.question.clone(),
answer: chat.answer.clone(),
created_at: chat.created_at.to_string(),
})
.collect();

Ok(rows)
})
}
24 changes: 11 additions & 13 deletions src-tauri/src/get_chatgpt_response.rs
Original file line number Diff line number Diff line change
@@ -1,3 +1,4 @@
use crate::app_type::ChatResponse;
use crate::database::Database;
use crate::get_db_connection::get_db_connection;
use crate::models::{ChatHistory, NewChatHistory};
Expand All @@ -7,27 +8,26 @@ use diesel::prelude::*;

use serde_json::json;
use tauri::State;
// Define a struct to hold both the response and the timestamp

#[tauri::command]
pub async fn get_chatgpt_response(
input_session_id: String,
message: String,
base64_images: Option<Vec<String>>, // Changed to a vector of strings
base64_images: Option<Vec<String>>,
model: String,
api_key: String,
db: State<'_, Database>,
) -> Result<String, String> {
// Use the helper function to get a mutable connection
) -> Result<ChatResponse, String> {
// Change return type here
let mut conn = get_db_connection(&db)?;

// Fetch previous chat history for the session
let session_history = chat_history
.filter(session_id.eq(&input_session_id))
.order(created_at.asc())
.load::<ChatHistory>(&mut conn)
.map_err(|e| e.to_string())?;

// Construct messages vector with the new format
let mut messages: Vec<_> = session_history
.iter()
.flat_map(|entry| {
Expand All @@ -48,7 +48,6 @@ pub async fn get_chatgpt_response(
})
.collect();

// Construct the user message including multiple base64 images if provided
let mut user_content = vec![json!({
"type": "text",
"text": message.clone()
Expand All @@ -72,13 +71,11 @@ pub async fn get_chatgpt_response(

println!("{:?}", messages);

// Create request body
let request_body = json!({
"model": model,
"messages": messages,
});

// Send request to OpenAI
let client = reqwest::Client::new();
let res = client
.post("https://api.openai.com/v1/chat/completions")
Expand All @@ -91,25 +88,26 @@ pub async fn get_chatgpt_response(
let json: serde_json::Value = res.json().await.map_err(|e| e.to_string())?;
println!("{:?}", json);

// Extract response content
let response = json["choices"][0]["message"]["content"]
.as_str()
.ok_or_else(|| "No response from API".to_string())?;

// Create new chat history entry
let now = Utc::now().naive_utc();
let new_chat = NewChatHistory {
session_id: &input_session_id,
question: &message, // Original message without image data
question: &message,
answer: response,
created_at: now,
};

// Insert new entry into the database
diesel::insert_into(chat_history)
.values(&new_chat)
.execute(&mut conn)
.map_err(|e| e.to_string())?;

Ok(response.to_string())
// Return the response along with the timestamp
Ok(ChatResponse {
response: response.to_string(),
created_at: now.to_string(), // Convert timestamp to string
})
}
28 changes: 28 additions & 0 deletions src-tauri/src/get_session_id_list.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,28 @@
use crate::database::Database;
use crate::get_db_connection::get_db_connection;
use crate::schema::chat_history::dsl::*;
use diesel::prelude::*;
use tauri::State;
use tauri::async_runtime::block_on;
use crate::app_type::SessionId;

#[tauri::command]
pub fn get_session_id_list(
db: State<'_, Database>,
) -> Result<Vec<SessionId>, String> {
block_on(async {
let mut conn = get_db_connection(&db)?;

let results = chat_history
.select(session_id)
.distinct()
.load::<String>(&mut conn)
.map_err(|e| e.to_string())?
.into_iter()
.map(SessionId)
.collect();

Ok(results)
})
}

13 changes: 10 additions & 3 deletions src-tauri/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -3,16 +3,19 @@ use std::env;
use std::fs;
use std::io::Write;

mod get_chatgpt_response;
mod app_type;
mod config;
mod database;
mod generate_session_id;
mod get_available_models;
mod get_chat_history;
mod get_chat_history_by_session;
mod get_chatgpt_response;
mod get_config;
mod get_db_connection;
mod get_default_model;
mod get_openai_api_key;
mod get_session_id_list;
mod models;
mod schema;
mod set_openai_api_key;
Expand All @@ -21,10 +24,12 @@ use database::Database;
use generate_session_id::generate_session_id;
use get_available_models::get_available_models;
use get_chat_history::get_chat_history;
use get_chat_history_by_session::get_chat_history_by_session;
use get_chatgpt_response::get_chatgpt_response;
use get_default_model::get_default_model;
use get_openai_api_key::get_openai_api_key;
use get_session_id_list::get_session_id_list;
use set_openai_api_key::set_openai_api_key;
use get_chatgpt_response::get_chatgpt_response;

fn shutdown(database: &Database) {
database
Expand Down Expand Up @@ -69,7 +74,9 @@ pub fn run() {
get_available_models,
get_default_model,
set_openai_api_key,
get_openai_api_key
get_openai_api_key,
get_chat_history_by_session,
get_session_id_list,
])
.run(tauri::generate_context!())
.expect("error while running tauri application");
Expand Down
Loading

0 comments on commit 1d46b68

Please sign in to comment.