Skip to content

Commit

Permalink
catch PromptError to show in alert window
Browse files Browse the repository at this point in the history
  • Loading branch information
aprxi committed Aug 4, 2024
1 parent 3918104 commit faa4d3f
Show file tree
Hide file tree
Showing 16 changed files with 219 additions and 98 deletions.
15 changes: 13 additions & 2 deletions lumni/src/apps/api/error.rs
Original file line number Diff line number Diff line change
@@ -1,3 +1,4 @@
use std::error::Error;
use std::fmt;

use rusqlite::Error as SqliteError;
Expand Down Expand Up @@ -38,6 +39,7 @@ pub enum ApplicationError {
DatabaseError(String),
NotImplemented(String),
NotReady(String),
CustomError(Box<dyn Error + Send + Sync>),
}

#[derive(Debug, Clone)]
Expand Down Expand Up @@ -132,11 +134,20 @@ impl fmt::Display for ApplicationError {
write!(f, "NotImplemented: {}", s)
}
ApplicationError::NotReady(s) => write!(f, "NotReady: {}", s),
ApplicationError::CustomError(e) => write!(f, "{}", e),
}
}
}

impl std::error::Error for ApplicationError {}
impl std::error::Error for ApplicationError {
fn source(&self) -> Option<&(dyn Error + 'static)> {
match self {
ApplicationError::CustomError(e) => Some(e.as_ref()),
// For other variants, we use the default behavior (returning None)
_ => None,
}
}
}

impl From<HttpClientError> for ApplicationError {
fn from(error: HttpClientError) -> Self {
Expand Down Expand Up @@ -192,4 +203,4 @@ impl From<std::string::String> for LumniError {
fn from(error: std::string::String) -> Self {
LumniError::Any(error.to_owned())
}
}
}
1 change: 1 addition & 0 deletions lumni/src/apps/builtin/llm/prompt/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@ pub mod src {
mod app;
mod chat;
mod defaults;
mod error;
mod handler;
mod server;
mod tui;
Expand Down
3 changes: 1 addition & 2 deletions lumni/src/apps/builtin/llm/prompt/src/app.rs
Original file line number Diff line number Diff line change
Expand Up @@ -197,8 +197,7 @@ async fn interactive_mode(
prompt_instruction: PromptInstruction,
db_conn: Arc<ConversationDatabase>,
) -> Result<(), ApplicationError> {
let app =
App::new(prompt_instruction, Arc::clone(&db_conn)).await?;
let app = App::new(prompt_instruction, Arc::clone(&db_conn)).await?;
let mut stdout = io::stdout().lock();

// Enable raw mode and setup the screen
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,8 @@ use super::db::{
};
use super::prepare::NewConversation;
use super::{
ChatCompletionOptions, ChatMessage, ColorScheme, PromptRole, TextLine,
ChatCompletionOptions, ChatMessage, ColorScheme, PromptError, PromptRole,
TextLine,
};
pub use crate::external as lumni;

Expand Down Expand Up @@ -352,8 +353,11 @@ impl PromptInstruction {
&mut self,
question: &str,
max_token_length: usize,
) -> Result<Vec<ChatMessage>, ApplicationError> {
let timestamp = Timestamp::from_system_time()?.as_millis();
) -> Result<Vec<ChatMessage>, PromptError> {
let timestamp = Timestamp::from_system_time()
.map_err(|e| PromptError::Runtime(e.to_string()))?
.as_millis();

let message = Message {
id: self.cache.new_message_id(),
conversation_id: self.cache.get_conversation_id(),
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -8,8 +8,8 @@ pub use prepare::NewConversation;

pub use super::db;
use super::{
ChatCompletionOptions, ChatMessage, ColorScheme, PromptRole, TextLine,
TextSegment,
ChatCompletionOptions, ChatMessage, ColorScheme, PromptError, PromptRole,
TextLine, TextSegment,
};

#[derive(Debug, Clone, PartialEq, Copy)]
Expand Down
2 changes: 1 addition & 1 deletion lumni/src/apps/builtin/llm/prompt/src/chat/db/connector.rs
Original file line number Diff line number Diff line change
Expand Up @@ -29,7 +29,7 @@ impl DatabaseConnector {
PRAGMA temp_store = MEMORY;
PRAGMA busy_timeout = 5000;
PRAGMA wal_autocheckpoint = 1000;
PRAGMA journal_size_limit = 67108864;"
PRAGMA journal_size_limit = 67108864;",
)?;

let operation_queue = Arc::new(Mutex::new(VecDeque::new()));
Expand Down
1 change: 1 addition & 0 deletions lumni/src/apps/builtin/llm/prompt/src/chat/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -12,6 +12,7 @@ pub use prompt::{AssistantManager, PromptRole};
pub use session::{prompt_app, App, ChatEvent, ThreadedChatSession};

pub use super::defaults::*;
pub use super::error::{PromptError, PromptNotReadyReason};
pub use super::server::{CompletionResponse, ModelServer, ServerManager};
use super::tui::{
draw_ui, AppUi, ColorScheme, ColorSchemeType, CommandLineAction,
Expand Down
Original file line number Diff line number Diff line change
@@ -1,8 +1,8 @@
use std::collections::HashMap;
use std::sync::Arc;
use uuid::Uuid;

use lumni::api::error::ApplicationError;
use uuid::Uuid;

use super::db::{ConversationDatabase, ConversationId};
use super::threaded_chat_session::ThreadedChatSession;
Expand Down Expand Up @@ -41,32 +41,40 @@ impl ChatSessionManager {
.model_server
.as_ref()
.map(|s| s.to_string());

let initial_session = ThreadedChatSession::new(
initial_prompt_instruction,
db_conn.clone(),
);

let mut sessions = HashMap::new();
sessions.insert(session_id, initial_session);

Self {
sessions,
active_session_info: SessionInfo {
id: session_id,
conversation_id,
server_name
active_session_info: SessionInfo {
id: session_id,
conversation_id,
server_name,
},
}
}

pub fn get_active_session(&mut self) -> Result<&mut ThreadedChatSession, ApplicationError> {
self.sessions.get_mut(&self.active_session_info.id).ok_or_else(||
ApplicationError::Runtime("Active session not found".to_string())
)
pub fn get_active_session(
&mut self,
) -> Result<&mut ThreadedChatSession, ApplicationError> {
self.sessions
.get_mut(&self.active_session_info.id)
.ok_or_else(|| {
ApplicationError::Runtime(
"Active session not found".to_string(),
)
})
}

pub fn get_conversation_id_for_active_session(&self) -> Option<ConversationId> {
pub fn get_conversation_id_for_active_session(
&self,
) -> Option<ConversationId> {
self.active_session_info.conversation_id
}

Expand All @@ -82,7 +90,9 @@ impl ChatSessionManager {
session.stop();
Ok(())
} else {
Err(ApplicationError::InvalidInput("Session not found".to_string()))
Err(ApplicationError::InvalidInput(
"Session not found".to_string(),
))
}
}

Expand Down Expand Up @@ -115,24 +125,30 @@ impl ChatSessionManager {
.model_server
.as_ref()
.map(|s| s.to_string());

self.active_session_info = SessionInfo {
id,
conversation_id,
server_name,
};
Ok(())
} else {
Err(ApplicationError::InvalidInput("Session not found".to_string()))
Err(ApplicationError::InvalidInput(
"Session not found".to_string(),
))
}
}

pub fn stop_active_chat_session(&mut self) -> Result<(), ApplicationError> {
if let Some(session) = self.sessions.get_mut(&self.active_session_info.id) {
if let Some(session) =
self.sessions.get_mut(&self.active_session_info.id)
{
session.stop();
Ok(())
} else {
Err(ApplicationError::Runtime("Active session not found".to_string()))
Err(ApplicationError::Runtime(
"Active session not found".to_string(),
))
}
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -32,8 +32,7 @@ pub async fn prompt_app<B: Backend>(
let mut key_event_handler = KeyEventHandler::new();
let mut redraw_ui = true;
let conversation_id = app.get_conversation_id_for_active_session();
let mut db_handler =
db_conn.get_conversation_handler(conversation_id);
let mut db_handler = db_conn.get_conversation_handler(conversation_id);

loop {
tokio::select! {
Expand Down Expand Up @@ -99,7 +98,11 @@ async fn handle_tick<B: Backend>(
)
.await?;
}
Event::Mouse(mouse_event) => handle_mouse_event(app, mouse_event),
Event::Mouse(mouse_event) => {
if !handle_mouse_event(app, mouse_event) {
return Ok(()); // skip redraw_ui if mouse event was not handled
}
}
_ => {}
}
*redraw_ui = true;
Expand Down Expand Up @@ -150,14 +153,19 @@ async fn handle_key_event(
Ok(())
}

fn handle_mouse_event(app: &mut App, mouse_event: MouseEvent) {
fn handle_mouse_event(app: &mut App, mouse_event: MouseEvent) -> bool {
// handle mouse events in response window
// return true if event was handled
let window = &mut app.ui.response;
match mouse_event.kind {
MouseEventKind::ScrollUp => window.scroll_up(),
MouseEventKind::ScrollDown => window.scroll_down(),
MouseEventKind::Down(_) => {}
_ => {}
_ => {
// ignore other mouse events
return false;
}
}
true // handled mouse event
}

async fn handle_prompt_action(
Expand Down Expand Up @@ -264,7 +272,6 @@ async fn send_prompt<'a>(
.get_active_session()?
.message(&formatted_prompt)
.await;

match result {
Ok(_) => {
// clear prompt
Expand All @@ -277,9 +284,9 @@ async fn send_prompt<'a>(
app.ui.set_primary_window(WindowKind::ResponseWindow);
app.ui.response.text_append("\n", Some(Style::reset()))?;
}
Err(e) => {
log::error!("Error sending message: {:?}", e);
app.ui.command_line.set_alert(&e.to_string())?;
Err(prompt_error) => {
// show error in alert window
app.ui.command_line.set_alert(&prompt_error.to_string())?;
}
}
Ok(())
Expand Down
13 changes: 9 additions & 4 deletions lumni/src/apps/builtin/llm/prompt/src/chat/session/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -17,8 +17,9 @@ use super::db::{ConversationDatabase, ConversationId};
use super::{
db, draw_ui, AppUi, ColorScheme, ColorSchemeType, CommandLineAction,
CompletionResponse, ConversationEvent, KeyEventHandler, ModalWindowType,
ModelServer, PromptAction, PromptInstruction, ServerManager,
TextWindowTrait, WindowEvent, WindowKind,
ModelServer, PromptAction, PromptError, PromptInstruction,
PromptNotReadyReason, ServerManager, TextWindowTrait, WindowEvent,
WindowKind,
};
pub use crate::external as lumni;

Expand Down Expand Up @@ -93,11 +94,15 @@ impl App<'_> {
Ok(())
}

pub fn get_conversation_id_for_active_session(&self) -> Option<ConversationId> {
pub fn get_conversation_id_for_active_session(
&self,
) -> Option<ConversationId> {
self.chat_manager.get_conversation_id_for_active_session()
}

pub async fn stop_active_chat_session(&mut self) -> Result<(), ApplicationError> {
pub async fn stop_active_chat_session(
&mut self,
) -> Result<(), ApplicationError> {
self.chat_manager.stop_active_chat_session()
}

Expand Down
Loading

0 comments on commit faa4d3f

Please sign in to comment.