International Rice Research Institute commited on
Commit
2387dcc
·
verified ·
1 Parent(s): 54e3727

Update app.R

Browse files
Files changed (1) hide show
  1. app.R +79 -248
app.R CHANGED
@@ -33,77 +33,67 @@ print("===================================")
33
 
34
  # ============================================================
35
  # AVAILABLE MODELS CONFIGURATION
36
- # Valid providers for HF Router: sambanova, together, fireworks-ai,
37
- # nebius, hyperbolic, novita, groq, cerebras, featherless-ai, hf-inference
38
- # Format: "model-id:provider" — never use ":auto"
39
  # ============================================================
40
 
41
  available_models <- list(
42
-
43
- # ── SambaNova (fastest, free tier) ──────────────────────
44
  list(
45
  id = "meta-llama/Llama-3.1-8B-Instruct:sambanova",
46
- label = "Llama 3.1 8B",
47
- provider = "SambaNova",
48
  tier = "free"
49
  ),
50
  list(
51
  id = "meta-llama/Llama-3.3-70B-Instruct:sambanova",
52
- label = "Llama 3.3 70B",
53
- provider = "SambaNova",
54
  tier = "free"
55
  ),
56
  list(
57
  id = "Qwen/Qwen2.5-72B-Instruct:sambanova",
58
- label = "Qwen 2.5 72B",
59
- provider = "SambaNova",
60
  tier = "free"
61
  ),
62
  list(
63
- id = "deepseek-ai/DeepSeek-V3-0324:sambanova",
64
- label = "DeepSeek-V3-0324",
65
- provider = "SambaNova",
66
  tier = "free"
67
  ),
68
-
69
- # ── Together AI ─────────────────────────────────────────
70
  list(
71
- id = "meta-llama/Llama-3.2-3B-Instruct:together",
72
- label = "Llama 3.2 3B",
73
- provider = "Together",
74
  tier = "free"
75
  ),
76
 
77
-
78
-
79
- # ── Groq (very fast) ────────────────────────────────────
80
  list(
81
- id = "meta-llama/Llama-3.3-70B-Instruct:groq",
82
- label = "Llama 3.3 70B",
83
- provider = "Groq",
84
  tier = "free"
85
  ),
86
  list(
87
- id = "meta-llama/Llama-3.1-8B-Instruct:groq",
88
- label = "Llama 3.1 8B",
89
- provider = "Groq",
90
  tier = "free"
91
  ),
92
 
93
-
94
-
95
- # ── HF Inference API ────────────────────────────────────
96
  list(
97
- id = "HuggingFaceTB/SmolLM3-3B:hf-inference",
98
- label = "SmolLM3",
99
- provider = "HF Inference",
100
  tier = "free"
101
  )
 
 
 
102
  )
103
 
104
  model_choices <- setNames(
105
  sapply(available_models, function(m) m$id),
106
- sapply(available_models, function(m) paste0("[", m$provider, "] ", m$label, " (", m$tier, ")"))
107
  )
108
 
109
  # ============================================================
@@ -163,45 +153,27 @@ if (use_hf_api) {
163
  # QUERY FUNCTION
164
  # ============================================================
165
 
166
- query_hf_api <- function(prompt, model_id = default_model, max_length = 500,
167
- temperature = 0.7, image_b64 = NULL, image_mime = "image/png") {
168
  if (!token_exists) return(list(success = FALSE, error = "HF_API_TOKEN not set"))
169
 
170
  tryCatch({
171
-
172
- # Build user content: plain text OR vision (image_url + text parts)
173
- user_content <- if (!is.null(image_b64)) {
174
- list(
175
- list(type = "image_url",
176
- image_url = list(url = paste0("data:", image_mime, ";base64,", image_b64))),
177
- list(type = "text", text = prompt)
178
- )
179
- } else {
180
- prompt # plain scalar string; auto_unbox keeps it as-is
181
- }
182
-
183
- body_list <- list(
184
- model = model_id,
185
- messages = list(
186
- list(role = "system",
187
- content = paste("You are an expert bioinformatics assistant specializing in QTL analysis.",
188
- "When an image is provided, describe and interpret it in a QTL/genomics context.",
189
- "Be concise and helpful.")),
190
- list(role = "user",
191
- content = user_content)
192
- ),
193
- max_tokens = as.integer(max_length),
194
- temperature = temperature
195
- )
196
-
197
  response <- POST(
198
  url = HF_API_URL,
199
  add_headers(
200
  Authorization = paste("Bearer", HF_API_TOKEN),
201
  "Content-Type" = "application/json"
202
  ),
203
- body = toJSON(body_list, auto_unbox = TRUE),
204
- encode = "json",
 
 
 
 
 
 
 
 
 
205
  timeout(60)
206
  )
207
 
@@ -442,38 +414,24 @@ enhanced_rule_response <- function(user_message, rv) {
442
  # AI RESPONSE GENERATION
443
  # ============================================================
444
 
445
- generate_ai_response <- function(user_message, rv, model_id = default_model,
446
- image_b64 = NULL, image_mime = "image/png") {
447
  context <- build_system_prompt(rv)
448
 
449
- if (token_exists) {
450
- # For image-only messages use a short prompt; otherwise include QTL context
451
- if (!is.null(image_b64) && nchar(trimws(user_message)) == 0) {
452
- prompt <- paste("Please analyse this image in the context of QTL / genomics research.",
453
- "Describe what you see and provide any relevant bioinformatics interpretation.")
454
- } else {
455
- prompt <- paste(
456
- "CONTEXT:", context,
457
- "\n\nUSER QUESTION:", user_message,
458
- "\n\nProvide a specific, helpful answer. Be concise but informative.",
459
- sep = "\n"
460
- )
461
- }
462
 
463
- result <- query_hf_api(prompt, model_id = model_id,
464
- image_b64 = image_b64, image_mime = image_mime)
465
 
466
  if (result$success) {
467
  return(result$text)
468
  } else {
469
- # If vision failed (model may not support it), tell the user clearly
470
- if (!is.null(image_b64)) {
471
- return(paste0("\u26a0\ufe0f This model does not support image input.\n\n",
472
- "Try a vision-capable model such as:\n",
473
- "\u2022 [SambaNova] Llama 3.3 70B\n",
474
- "\u2022 [Together] Llama 3.2 3B\n\n",
475
- "API error: ", result$error))
476
- }
477
  message("API Error: ", result$error)
478
  return(enhanced_rule_response(user_message, rv))
479
  }
@@ -859,18 +817,14 @@ ui <- fluidPage(
859
  tags$thead(tags$tr(
860
  tags$th(style = "text-align:left; padding:6px; border-bottom:1px solid #30363d; color:#58a6ff;", "Model"),
861
  tags$th(style = "text-align:left; padding:6px; border-bottom:1px solid #30363d; color:#58a6ff;", "Provider"),
862
- tags$th(style = "text-align:left; padding:6px; border-bottom:1px solid #30363d; color:#58a6ff;", "Model ID"),
863
  tags$th(style = "text-align:left; padding:6px; border-bottom:1px solid #30363d; color:#58a6ff;", "Tier")
864
  )),
865
  tags$tbody(
866
  lapply(available_models, function(m) {
867
- tier_color <- if (m$tier == "free") "#3fb950" else "#d29922"
868
  tags$tr(
869
  tags$td(style = "padding:6px; border-bottom:1px solid #21262d;", m$label),
870
  tags$td(style = "padding:6px; border-bottom:1px solid #21262d;", m$provider),
871
- tags$td(style = "padding:6px; border-bottom:1px solid #21262d; font-family:'IBM Plex Mono'; font-size:11px; color:#6e7681;",
872
- gsub(":.*$", "", m$id)),
873
- tags$td(style = paste0("padding:6px; border-bottom:1px solid #21262d; color:", tier_color, ";"), m$tier)
874
  )
875
  })
876
  )
@@ -1027,10 +981,7 @@ server <- function(input, output, session) {
1027
  current_model = default_model,
1028
  model_test_status = if (use_hf_api) "online" else "offline",
1029
  pending_file_content = NULL,
1030
- pending_file_name = NULL,
1031
- pending_image_b64 = NULL,
1032
- pending_image_mime = NULL,
1033
- pending_image_thumb = NULL # data URI for thumbnail preview
1034
  )
1035
 
1036
  # ---- Current selected model ----
@@ -1065,80 +1016,42 @@ server <- function(input, output, session) {
1065
  })
1066
 
1067
  # ---- Chat helpers ----
1068
- add_message <- function(role, content, model_used = NULL,
1069
- image_thumb = NULL, image_name = NULL) {
1070
  timestamp <- format(Sys.time(), "%H:%M")
1071
  values$chat_messages <- c(values$chat_messages,
1072
- list(list(role = role,
1073
- content = content,
1074
- time = timestamp,
1075
- model = model_used,
1076
- image_thumb = image_thumb,
1077
- image_name = image_name)))
1078
  if (length(values$chat_messages) > 100)
1079
  values$chat_messages <- tail(values$chat_messages, 100)
1080
  session$sendCustomMessage("scrollChatBottom", list())
1081
  }
1082
 
1083
- process_message <- function(user_text,
1084
- file_content = NULL, file_name = NULL,
1085
- image_b64 = NULL, image_mime = NULL,
1086
- image_thumb = NULL) {
1087
- has_text <- nchar(trimws(user_text)) > 0
1088
- has_file <- !is.null(file_content)
1089
- has_image <- !is.null(image_b64)
1090
-
1091
- if (!has_text && !has_file && !has_image) return()
1092
 
1093
- # ── Build display message for user bubble ──
1094
- display_text <- user_text
1095
- if (has_file && nchar(trimws(file_content)) > 0) {
1096
- display_text <- paste0(user_text,
1097
- if (has_text) "\n\n" else "",
1098
- "\U0001f4ce ", file_name)
1099
- }
1100
- if (has_image) {
1101
- # We pass thumbnail separately so the bubble can render it
1102
- display_text <- paste0(if (has_text) user_text else "",
1103
- if (has_text) "\n" else "",
1104
- "\U0001f5bc\ufe0f ", file_name)
1105
  }
1106
 
1107
- add_message("user", display_text,
1108
- image_thumb = image_thumb, image_name = if (has_image) file_name else NULL)
1109
-
1110
  values$is_typing <- TRUE
1111
 
1112
  model_id <- isolate(values$current_model)
1113
-
1114
- # ── Build prompt (text + file context) ──
1115
- prompt_text <- user_text
1116
- if (has_file) {
1117
- prompt_text <- paste0(user_text,
1118
- if (has_text) "\n\n" else "",
1119
- "--- Attached file: ", file_name, " ---\n",
1120
- substr(file_content, 1, 3000),
1121
- if (nchar(file_content) > 3000) "\n[... truncated ...]" else "")
1122
- }
1123
- if (has_image && !has_text && !has_file) {
1124
- prompt_text <- "Please analyse this image in the context of QTL/genomics research."
1125
- }
1126
-
1127
- response <- generate_ai_response(prompt_text, values,
1128
- model_id = model_id,
1129
- image_b64 = image_b64,
1130
- image_mime = if (!is.null(image_mime)) image_mime else "image/png")
1131
 
1132
  values$is_typing <- FALSE
1133
  model_short <- gsub(".*/([^:]+):.*", "\\1", model_id)
1134
  add_message("assistant", response, model_used = if (token_exists) model_short else NULL)
1135
 
1136
- # Clear all pending attachments
1137
  values$pending_file_content <- NULL
1138
  values$pending_file_name <- NULL
1139
- values$pending_image_b64 <- NULL
1140
- values$pending_image_mime <- NULL
1141
- values$pending_image_thumb <- NULL
1142
  }
1143
 
1144
  # ---- Handle chat file upload ----
@@ -1148,107 +1061,42 @@ server <- function(input, output, session) {
1148
  file_name <- input$chat_file_upload$name
1149
  ext <- tolower(tools::file_ext(file_name))
1150
 
1151
- # Reset previous pending files
1152
- values$pending_file_content <- NULL
1153
- values$pending_file_name <- NULL
1154
- values$pending_image_b64 <- NULL
1155
- values$pending_image_mime <- NULL
1156
- values$pending_image_thumb <- NULL
1157
-
1158
  tryCatch({
1159
- if (ext %in% c("png", "jpg", "jpeg", "gif", "webp", "bmp")) {
1160
- # ── IMAGE: read as base64, build data URI thumbnail ──
1161
- mime_map <- c(png = "image/png", jpg = "image/jpeg", jpeg = "image/jpeg",
1162
- gif = "image/gif", webp = "image/webp", bmp = "image/bmp")
1163
- mime_type <- unname(mime_map[ext])
1164
- if (is.na(mime_type)) mime_type <- "image/png"
1165
-
1166
- raw_bytes <- readBin(file_path, "raw", file.info(file_path)$size)
1167
- b64_string <- base64enc::base64encode(raw_bytes)
1168
- data_uri <- paste0("data:", mime_type, ";base64,", b64_string)
1169
-
1170
- values$pending_image_b64 <- b64_string
1171
- values$pending_image_mime <- mime_type
1172
- values$pending_image_thumb <- data_uri
1173
- values$pending_file_name <- file_name
1174
-
1175
- showNotification(paste0("Image ready: ", file_name), type = "message")
1176
-
1177
- } else if (ext %in% c("csv", "txt", "tsv")) {
1178
- # ── TEXT files: read lines ──
1179
- file_content <- paste(readLines(file_path, n = 200), collapse = "\n")
1180
- values$pending_file_content <- file_content
1181
- values$pending_file_name <- file_name
1182
-
1183
- } else if (ext == "xlsx") {
1184
- # ── EXCEL: read with readxl if available ──
1185
- if (requireNamespace("readxl", quietly = TRUE)) {
1186
- df <- readxl::read_excel(file_path)
1187
- file_content <- paste(capture.output(print(head(df, 20))), collapse = "\n")
1188
- values$pending_file_content <- paste0("[Excel: ", file_name, "]\n", file_content)
1189
- } else {
1190
- values$pending_file_content <- paste0("[Excel file: ", file_name,
1191
- " - install readxl to parse content]")
1192
- }
1193
- values$pending_file_name <- file_name
1194
-
1195
- } else if (ext == "pdf") {
1196
- # ── PDF: extract text with pdftools if available ──
1197
- if (requireNamespace("pdftools", quietly = TRUE)) {
1198
- txt <- pdftools::pdf_text(file_path)
1199
- file_content <- substr(paste(txt, collapse = "\n"), 1, 3000)
1200
- values$pending_file_content <- paste0("[PDF: ", file_name, "]\n", file_content)
1201
- } else {
1202
- values$pending_file_content <- paste0("[PDF file: ", file_name,
1203
- " - install pdftools to parse content]")
1204
- }
1205
- values$pending_file_name <- file_name
1206
-
1207
  } else {
1208
- values$pending_file_content <- paste0("[File: ", file_name, " (",
1209
- round(file.info(file_path)$size / 1024, 1), " KB)]")
1210
- values$pending_file_name <- file_name
1211
  }
1212
 
 
 
1213
  }, error = function(e) {
1214
  showNotification(paste("Could not read file:", e$message), type = "warning")
1215
  })
1216
  })
1217
 
1218
- # ---- Clear chat file / image ----
1219
  observeEvent(input$clear_chat_file, {
1220
  values$pending_file_content <- NULL
1221
  values$pending_file_name <- NULL
1222
- values$pending_image_b64 <- NULL
1223
- values$pending_image_mime <- NULL
1224
- values$pending_image_thumb <- NULL
1225
  })
1226
 
1227
  # ---- Send chat ----
1228
  observeEvent(input$send_chat, {
1229
- user_text <- trimws(input$chat_input)
1230
  file_content <- isolate(values$pending_file_content)
1231
  file_name <- isolate(values$pending_file_name)
1232
- image_b64 <- isolate(values$pending_image_b64)
1233
- image_mime <- isolate(values$pending_image_mime)
1234
- image_thumb <- isolate(values$pending_image_thumb)
1235
- img_name <- isolate(values$pending_file_name) # same field used for images
1236
 
1237
- has_anything <- nchar(user_text) > 0 || !is.null(file_content) || !is.null(image_b64)
1238
- if (!has_anything) return()
1239
 
1240
  updateTextAreaInput(session, "chat_input", value = "")
 
1241
  shinyjs::runjs("
1242
  document.getElementById('chat_file_preview').style.display = 'none';
1243
  document.getElementById('chat_file_preview').innerHTML = '';
1244
  ")
1245
 
1246
- process_message(user_text,
1247
- file_content = file_content,
1248
- file_name = file_name,
1249
- image_b64 = image_b64,
1250
- image_mime = image_mime,
1251
- image_thumb = image_thumb)
1252
  })
1253
 
1254
  observeEvent(input$quick_q, { req(input$quick_q); process_message(input$quick_q) })
@@ -1268,7 +1116,7 @@ server <- function(input, output, session) {
1268
  "I'm using rule-based responses. Set **HF_API_TOKEN** in Space secrets to enable AI models."
1269
  }
1270
  add_message("assistant", paste0(
1271
- "\U0001f44b Hello! I'm your QTL analysis assistant.\n\n",
1272
  mode_msg,
1273
  "\n\n**I can help you with:**\n",
1274
  "\u2022 **What is PVE?** - Understand variance explained\n",
@@ -1289,21 +1137,6 @@ server <- function(input, output, session) {
1289
  elems <- lapply(messages, function(msg) {
1290
  content_html <- HTML(gsub("\n", "<br>", htmltools::htmlEscape(msg$content)))
1291
 
1292
- # Render image thumbnail inside user bubble if present
1293
- image_tag <- if (!is.null(msg$image_thumb)) {
1294
- tags$div(
1295
- style = "margin-top:8px;",
1296
- tags$img(
1297
- src = msg$image_thumb,
1298
- alt = if (!is.null(msg$image_name)) msg$image_name else "uploaded image",
1299
- style = paste0("max-width:100%; max-height:200px; border-radius:8px;",
1300
- "border:1px solid rgba(255,255,255,0.2); display:block;")
1301
- ),
1302
- if (!is.null(msg$image_name))
1303
- tags$div(style = "font-size:10px; opacity:0.7; margin-top:3px;", msg$image_name)
1304
- )
1305
- } else NULL
1306
-
1307
  meta_content <- tagList(
1308
  span(msg$time),
1309
  if (!is.null(msg$model) && msg$role == "assistant")
@@ -1311,9 +1144,7 @@ server <- function(input, output, session) {
1311
  )
1312
 
1313
  div(class = paste("chat-msg", msg$role),
1314
- div(class = "chat-bubble",
1315
- content_html,
1316
- image_tag),
1317
  div(class = "chat-meta", meta_content))
1318
  })
1319
 
@@ -2044,7 +1875,7 @@ server <- function(input, output, session) {
2044
  }
2045
 
2046
  # ============================================================
2047
- # RUN APP
2048
  # ============================================================
2049
 
2050
  shinyApp(ui = ui, server = server)
 
33
 
34
  # ============================================================
35
  # AVAILABLE MODELS CONFIGURATION
 
 
 
36
  # ============================================================
37
 
38
  available_models <- list(
 
 
39
  list(
40
  id = "meta-llama/Llama-3.1-8B-Instruct:sambanova",
41
+ label = "Llama 3.1 8B (SambaNova)",
42
+ provider = "sambanova",
43
  tier = "free"
44
  ),
45
  list(
46
  id = "meta-llama/Llama-3.3-70B-Instruct:sambanova",
47
+ label = "Llama 3.3 70B (SambaNova)",
48
+ provider = "sambanova",
49
  tier = "free"
50
  ),
51
  list(
52
  id = "Qwen/Qwen2.5-72B-Instruct:sambanova",
53
+ label = "Qwen 2.5 72B (SambaNova)",
54
+ provider = "sambanova",
55
  tier = "free"
56
  ),
57
  list(
58
+ id = "meta-llama/Llama-3.2-3B-Instruct:together",
59
+ label = "Llama 3.2 3B (Together)",
60
+ provider = "together",
61
  tier = "free"
62
  ),
 
 
63
  list(
64
+ id = "Qwen/Qwen2.5-7B-Instruct:together",
65
+ label = "Qwen 2.5 7B (Together)",
66
+ provider = "together",
67
  tier = "free"
68
  ),
69
 
 
 
 
70
  list(
71
+ id = "HuggingFaceTB/SmolLM3-3B:hf-inference",
72
+ label = "SmolLM3",
73
+ provider = "together",
74
  tier = "free"
75
  ),
76
  list(
77
+ id = "deepseek-ai/DeepSeek-V3-0324:sambanova",
78
+ label = "Deepseek",
79
+ provider = "together",
80
  tier = "free"
81
  ),
82
 
 
 
 
83
  list(
84
+ id = "meta-llama/Llama-3.2-3B-Instruct:together",
85
+ label = "meta-llma",
86
+ provider = "together",
87
  tier = "free"
88
  )
89
+
90
+
91
+
92
  )
93
 
94
  model_choices <- setNames(
95
  sapply(available_models, function(m) m$id),
96
+ sapply(available_models, function(m) paste0(m$label, " [", m$tier, "]"))
97
  )
98
 
99
  # ============================================================
 
153
  # QUERY FUNCTION
154
  # ============================================================
155
 
156
+ query_hf_api <- function(prompt, model_id = default_model, max_length = 500, temperature = 0.7) {
 
157
  if (!token_exists) return(list(success = FALSE, error = "HF_API_TOKEN not set"))
158
 
159
  tryCatch({
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
160
  response <- POST(
161
  url = HF_API_URL,
162
  add_headers(
163
  Authorization = paste("Bearer", HF_API_TOKEN),
164
  "Content-Type" = "application/json"
165
  ),
166
+ body = toJSON(list(
167
+ model = model_id,
168
+ messages = list(
169
+ list(role = "system",
170
+ content = "You are an expert bioinformatics assistant specializing in QTL analysis. Be concise and helpful."),
171
+ list(role = "user", content = prompt)
172
+ ),
173
+ max_tokens = as.integer(max_length),
174
+ temperature = temperature
175
+ ), auto_unbox = TRUE),
176
+ encode = "json",
177
  timeout(60)
178
  )
179
 
 
414
  # AI RESPONSE GENERATION
415
  # ============================================================
416
 
417
+ generate_ai_response <- function(user_message, rv, model_id = default_model) {
 
418
  context <- build_system_prompt(rv)
419
 
420
+ current_use_api <- token_exists
421
+
422
+ if (current_use_api) {
423
+ prompt <- paste(
424
+ "CONTEXT:", context,
425
+ "\n\nUSER QUESTION:", user_message,
426
+ "\n\nProvide a specific, helpful answer based ONLY on the context above. Be concise but informative.",
427
+ sep = "\n"
428
+ )
 
 
 
 
429
 
430
+ result <- query_hf_api(prompt, model_id = model_id)
 
431
 
432
  if (result$success) {
433
  return(result$text)
434
  } else {
 
 
 
 
 
 
 
 
435
  message("API Error: ", result$error)
436
  return(enhanced_rule_response(user_message, rv))
437
  }
 
817
  tags$thead(tags$tr(
818
  tags$th(style = "text-align:left; padding:6px; border-bottom:1px solid #30363d; color:#58a6ff;", "Model"),
819
  tags$th(style = "text-align:left; padding:6px; border-bottom:1px solid #30363d; color:#58a6ff;", "Provider"),
 
820
  tags$th(style = "text-align:left; padding:6px; border-bottom:1px solid #30363d; color:#58a6ff;", "Tier")
821
  )),
822
  tags$tbody(
823
  lapply(available_models, function(m) {
 
824
  tags$tr(
825
  tags$td(style = "padding:6px; border-bottom:1px solid #21262d;", m$label),
826
  tags$td(style = "padding:6px; border-bottom:1px solid #21262d;", m$provider),
827
+ tags$td(style = "padding:6px; border-bottom:1px solid #21262d;", tags$span(style = "color:#3fb950;", m$tier))
 
 
828
  )
829
  })
830
  )
 
981
  current_model = default_model,
982
  model_test_status = if (use_hf_api) "online" else "offline",
983
  pending_file_content = NULL,
984
+ pending_file_name = NULL
 
 
 
985
  )
986
 
987
  # ---- Current selected model ----
 
1016
  })
1017
 
1018
  # ---- Chat helpers ----
1019
+ add_message <- function(role, content, model_used = NULL) {
 
1020
  timestamp <- format(Sys.time(), "%H:%M")
1021
  values$chat_messages <- c(values$chat_messages,
1022
+ list(list(role = role, content = content,
1023
+ time = timestamp, model = model_used)))
 
 
 
 
1024
  if (length(values$chat_messages) > 100)
1025
  values$chat_messages <- tail(values$chat_messages, 100)
1026
  session$sendCustomMessage("scrollChatBottom", list())
1027
  }
1028
 
1029
+ process_message <- function(user_text, file_content = NULL, file_name = NULL) {
1030
+ if (nchar(trimws(user_text)) == 0 && is.null(file_content)) return()
 
 
 
 
 
 
 
1031
 
1032
+ # Build full message including file content if present
1033
+ full_message <- user_text
1034
+ if (!is.null(file_content) && nchar(trimws(file_content)) > 0) {
1035
+ full_message <- paste0(user_text,
1036
+ if (nchar(trimws(user_text)) > 0) "\n\n" else "",
1037
+ "--- Attached file: ", file_name, " ---\n",
1038
+ substr(file_content, 1, 3000),
1039
+ if (nchar(file_content) > 3000) "\n[... truncated ...]" else "")
 
 
 
 
1040
  }
1041
 
1042
+ add_message("user", full_message)
 
 
1043
  values$is_typing <- TRUE
1044
 
1045
  model_id <- isolate(values$current_model)
1046
+ response <- generate_ai_response(full_message, values, model_id = model_id)
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1047
 
1048
  values$is_typing <- FALSE
1049
  model_short <- gsub(".*/([^:]+):.*", "\\1", model_id)
1050
  add_message("assistant", response, model_used = if (token_exists) model_short else NULL)
1051
 
1052
+ # Clear pending file
1053
  values$pending_file_content <- NULL
1054
  values$pending_file_name <- NULL
 
 
 
1055
  }
1056
 
1057
  # ---- Handle chat file upload ----
 
1061
  file_name <- input$chat_file_upload$name
1062
  ext <- tolower(tools::file_ext(file_name))
1063
 
 
 
 
 
 
 
 
1064
  tryCatch({
1065
+ file_content <- if (ext %in% c("csv", "txt", "tsv")) {
1066
+ paste(readLines(file_path, n = 200), collapse = "\n")
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1067
  } else {
1068
+ paste0("[Binary file: ", file_name, " - ", round(file.info(file_path)$size / 1024, 1), " KB]")
 
 
1069
  }
1070
 
1071
+ values$pending_file_content <- file_content
1072
+ values$pending_file_name <- file_name
1073
  }, error = function(e) {
1074
  showNotification(paste("Could not read file:", e$message), type = "warning")
1075
  })
1076
  })
1077
 
1078
+ # ---- Clear chat file ----
1079
  observeEvent(input$clear_chat_file, {
1080
  values$pending_file_content <- NULL
1081
  values$pending_file_name <- NULL
 
 
 
1082
  })
1083
 
1084
  # ---- Send chat ----
1085
  observeEvent(input$send_chat, {
1086
+ user_text <- trimws(input$chat_input)
1087
  file_content <- isolate(values$pending_file_content)
1088
  file_name <- isolate(values$pending_file_name)
 
 
 
 
1089
 
1090
+ if (nchar(user_text) == 0 && is.null(file_content)) return()
 
1091
 
1092
  updateTextAreaInput(session, "chat_input", value = "")
1093
+ # Clear file preview via JS
1094
  shinyjs::runjs("
1095
  document.getElementById('chat_file_preview').style.display = 'none';
1096
  document.getElementById('chat_file_preview').innerHTML = '';
1097
  ")
1098
 
1099
+ process_message(user_text, file_content, file_name)
 
 
 
 
 
1100
  })
1101
 
1102
  observeEvent(input$quick_q, { req(input$quick_q); process_message(input$quick_q) })
 
1116
  "I'm using rule-based responses. Set **HF_API_TOKEN** in Space secrets to enable AI models."
1117
  }
1118
  add_message("assistant", paste0(
1119
+ "\U0001f44b Vanakam! I'm TerraByte - An AI powered companion.\n\n",
1120
  mode_msg,
1121
  "\n\n**I can help you with:**\n",
1122
  "\u2022 **What is PVE?** - Understand variance explained\n",
 
1137
  elems <- lapply(messages, function(msg) {
1138
  content_html <- HTML(gsub("\n", "<br>", htmltools::htmlEscape(msg$content)))
1139
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1140
  meta_content <- tagList(
1141
  span(msg$time),
1142
  if (!is.null(msg$model) && msg$role == "assistant")
 
1144
  )
1145
 
1146
  div(class = paste("chat-msg", msg$role),
1147
+ div(class = "chat-bubble", content_html),
 
 
1148
  div(class = "chat-meta", meta_content))
1149
  })
1150
 
 
1875
  }
1876
 
1877
  # ============================================================
1878
+ # RUN APP#
1879
  # ============================================================
1880
 
1881
  shinyApp(ui = ui, server = server)