International Rice Research Institute commited on
Commit
7530fd2
·
verified ·
1 Parent(s): 99ec9e1

Update app.R

Browse files
Files changed (1) hide show
  1. app.R +77 -286
app.R CHANGED
@@ -33,115 +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
  list(
77
  id = "Qwen/Qwen2.5-7B-Instruct:together",
78
- label = "Qwen 2.5 7B",
79
- provider = "Together",
80
  tier = "free"
81
  ),
82
- list(
83
- id = "deepseek-ai/DeepSeek-V3-0324:together",
84
- label = "DeepSeek-V3-0324",
85
- provider = "Together",
86
- tier = "paid"
87
- ),
88
 
89
- # ── Nebius AI Studio ────────────────────────────────────
90
  list(
91
- id = "deepseek-ai/DeepSeek-V3-0324:nebius",
92
- label = "DeepSeek-V3-0324",
93
- provider = "Nebius",
94
- tier = "paid"
95
- ),
96
- list(
97
- id = "meta-llama/Llama-3.3-70B-Instruct:nebius",
98
- label = "Llama 3.3 70B",
99
- provider = "Nebius",
100
- tier = "paid"
101
- ),
102
-
103
- # ── Fireworks AI ────────────────────────────────────────
104
- list(
105
- id = "deepseek-ai/DeepSeek-V3-0324:fireworks-ai",
106
- label = "DeepSeek-V3-0324",
107
- provider = "Fireworks",
108
- tier = "paid"
109
- ),
110
-
111
- # ── Groq (very fast) ────────────────────────────────────
112
- list(
113
- id = "meta-llama/Llama-3.3-70B-Instruct:groq",
114
- label = "Llama 3.3 70B",
115
- provider = "Groq",
116
  tier = "free"
117
  ),
118
  list(
119
- id = "meta-llama/Llama-3.1-8B-Instruct:groq",
120
- label = "Llama 3.1 8B",
121
- provider = "Groq",
122
- tier = "free"
123
- ),
124
-
125
- # ── Cerebras ────────────────────────────────────────────
126
- list(
127
- id = "meta-llama/Llama-3.1-8B-Instruct:cerebras",
128
- label = "Llama 3.1 8B",
129
- provider = "Cerebras",
130
  tier = "free"
131
  ),
132
 
133
- # ── HF Inference API ────────────────────────────────────
134
  list(
135
- id = "Qwen/Qwen2.5-7B-Instruct:hf-inference",
136
- label = "Qwen 2.5 7B",
137
- provider = "HF Inference",
138
  tier = "free"
139
  )
 
 
 
140
  )
141
 
142
  model_choices <- setNames(
143
  sapply(available_models, function(m) m$id),
144
- sapply(available_models, function(m) paste0("[", m$provider, "] ", m$label, " (", m$tier, ")"))
145
  )
146
 
147
  # ============================================================
@@ -201,45 +153,27 @@ if (use_hf_api) {
201
  # QUERY FUNCTION
202
  # ============================================================
203
 
204
- query_hf_api <- function(prompt, model_id = default_model, max_length = 500,
205
- temperature = 0.7, image_b64 = NULL, image_mime = "image/png") {
206
  if (!token_exists) return(list(success = FALSE, error = "HF_API_TOKEN not set"))
207
 
208
  tryCatch({
209
-
210
- # Build user content: plain text OR vision (image_url + text parts)
211
- user_content <- if (!is.null(image_b64)) {
212
- list(
213
- list(type = "image_url",
214
- image_url = list(url = paste0("data:", image_mime, ";base64,", image_b64))),
215
- list(type = "text", text = prompt)
216
- )
217
- } else {
218
- prompt # plain scalar string; auto_unbox keeps it as-is
219
- }
220
-
221
- body_list <- list(
222
- model = model_id,
223
- messages = list(
224
- list(role = "system",
225
- content = paste("You are an expert bioinformatics assistant specializing in QTL analysis.",
226
- "When an image is provided, describe and interpret it in a QTL/genomics context.",
227
- "Be concise and helpful.")),
228
- list(role = "user",
229
- content = user_content)
230
- ),
231
- max_tokens = as.integer(max_length),
232
- temperature = temperature
233
- )
234
-
235
  response <- POST(
236
  url = HF_API_URL,
237
  add_headers(
238
  Authorization = paste("Bearer", HF_API_TOKEN),
239
  "Content-Type" = "application/json"
240
  ),
241
- body = toJSON(body_list, auto_unbox = TRUE),
242
- encode = "json",
 
 
 
 
 
 
 
 
 
243
  timeout(60)
244
  )
245
 
@@ -480,38 +414,24 @@ enhanced_rule_response <- function(user_message, rv) {
480
  # AI RESPONSE GENERATION
481
  # ============================================================
482
 
483
- generate_ai_response <- function(user_message, rv, model_id = default_model,
484
- image_b64 = NULL, image_mime = "image/png") {
485
  context <- build_system_prompt(rv)
486
 
487
- if (token_exists) {
488
- # For image-only messages use a short prompt; otherwise include QTL context
489
- if (!is.null(image_b64) && nchar(trimws(user_message)) == 0) {
490
- prompt <- paste("Please analyse this image in the context of QTL / genomics research.",
491
- "Describe what you see and provide any relevant bioinformatics interpretation.")
492
- } else {
493
- prompt <- paste(
494
- "CONTEXT:", context,
495
- "\n\nUSER QUESTION:", user_message,
496
- "\n\nProvide a specific, helpful answer. Be concise but informative.",
497
- sep = "\n"
498
- )
499
- }
500
 
501
- result <- query_hf_api(prompt, model_id = model_id,
502
- image_b64 = image_b64, image_mime = image_mime)
503
 
504
  if (result$success) {
505
  return(result$text)
506
  } else {
507
- # If vision failed (model may not support it), tell the user clearly
508
- if (!is.null(image_b64)) {
509
- return(paste0("\u26a0\ufe0f This model does not support image input.\n\n",
510
- "Try a vision-capable model such as:\n",
511
- "\u2022 [SambaNova] Llama 3.3 70B\n",
512
- "\u2022 [Together] Llama 3.2 3B\n\n",
513
- "API error: ", result$error))
514
- }
515
  message("API Error: ", result$error)
516
  return(enhanced_rule_response(user_message, rv))
517
  }
@@ -897,18 +817,14 @@ ui <- fluidPage(
897
  tags$thead(tags$tr(
898
  tags$th(style = "text-align:left; padding:6px; border-bottom:1px solid #30363d; color:#58a6ff;", "Model"),
899
  tags$th(style = "text-align:left; padding:6px; border-bottom:1px solid #30363d; color:#58a6ff;", "Provider"),
900
- tags$th(style = "text-align:left; padding:6px; border-bottom:1px solid #30363d; color:#58a6ff;", "Model ID"),
901
  tags$th(style = "text-align:left; padding:6px; border-bottom:1px solid #30363d; color:#58a6ff;", "Tier")
902
  )),
903
  tags$tbody(
904
  lapply(available_models, function(m) {
905
- tier_color <- if (m$tier == "free") "#3fb950" else "#d29922"
906
  tags$tr(
907
  tags$td(style = "padding:6px; border-bottom:1px solid #21262d;", m$label),
908
  tags$td(style = "padding:6px; border-bottom:1px solid #21262d;", m$provider),
909
- tags$td(style = "padding:6px; border-bottom:1px solid #21262d; font-family:'IBM Plex Mono'; font-size:11px; color:#6e7681;",
910
- gsub(":.*$", "", m$id)),
911
- tags$td(style = paste0("padding:6px; border-bottom:1px solid #21262d; color:", tier_color, ";"), m$tier)
912
  )
913
  })
914
  )
@@ -988,7 +904,7 @@ ui <- fluidPage(
988
  tags$i(class = "fas fa-paperclip"),
989
  " Attach file",
990
  fileInput("chat_file_upload", label = NULL,
991
- accept = c(".csv", ".txt", ".tsv", ".xlsx", ".pdf", ".png", ".jpg", ".jpeg", ".gif", ".webp"),
992
  buttonLabel = "",
993
  placeholder = "",
994
  width = "0px")
@@ -1065,10 +981,7 @@ server <- function(input, output, session) {
1065
  current_model = default_model,
1066
  model_test_status = if (use_hf_api) "online" else "offline",
1067
  pending_file_content = NULL,
1068
- pending_file_name = NULL,
1069
- pending_image_b64 = NULL,
1070
- pending_image_mime = NULL,
1071
- pending_image_thumb = NULL # data URI for thumbnail preview
1072
  )
1073
 
1074
  # ---- Current selected model ----
@@ -1103,80 +1016,42 @@ server <- function(input, output, session) {
1103
  })
1104
 
1105
  # ---- Chat helpers ----
1106
- add_message <- function(role, content, model_used = NULL,
1107
- image_thumb = NULL, image_name = NULL) {
1108
  timestamp <- format(Sys.time(), "%H:%M")
1109
  values$chat_messages <- c(values$chat_messages,
1110
- list(list(role = role,
1111
- content = content,
1112
- time = timestamp,
1113
- model = model_used,
1114
- image_thumb = image_thumb,
1115
- image_name = image_name)))
1116
  if (length(values$chat_messages) > 100)
1117
  values$chat_messages <- tail(values$chat_messages, 100)
1118
  session$sendCustomMessage("scrollChatBottom", list())
1119
  }
1120
 
1121
- process_message <- function(user_text,
1122
- file_content = NULL, file_name = NULL,
1123
- image_b64 = NULL, image_mime = NULL,
1124
- image_thumb = NULL) {
1125
- has_text <- nchar(trimws(user_text)) > 0
1126
- has_file <- !is.null(file_content)
1127
- has_image <- !is.null(image_b64)
1128
 
1129
- if (!has_text && !has_file && !has_image) return()
1130
-
1131
- # ── Build display message for user bubble ──
1132
- display_text <- user_text
1133
- if (has_file && nchar(trimws(file_content)) > 0) {
1134
- display_text <- paste0(user_text,
1135
- if (has_text) "\n\n" else "",
1136
- "\U0001f4ce ", file_name)
1137
- }
1138
- if (has_image) {
1139
- # We pass thumbnail separately so the bubble can render it
1140
- display_text <- paste0(if (has_text) user_text else "",
1141
- if (has_text) "\n" else "",
1142
- "\U0001f5bc\ufe0f ", file_name)
1143
  }
1144
 
1145
- add_message("user", display_text,
1146
- image_thumb = image_thumb, image_name = if (has_image) file_name else NULL)
1147
-
1148
  values$is_typing <- TRUE
1149
 
1150
  model_id <- isolate(values$current_model)
1151
-
1152
- # ── Build prompt (text + file context) ──
1153
- prompt_text <- user_text
1154
- if (has_file) {
1155
- prompt_text <- paste0(user_text,
1156
- if (has_text) "\n\n" else "",
1157
- "--- Attached file: ", file_name, " ---\n",
1158
- substr(file_content, 1, 3000),
1159
- if (nchar(file_content) > 3000) "\n[... truncated ...]" else "")
1160
- }
1161
- if (has_image && !has_text && !has_file) {
1162
- prompt_text <- "Please analyse this image in the context of QTL/genomics research."
1163
- }
1164
-
1165
- response <- generate_ai_response(prompt_text, values,
1166
- model_id = model_id,
1167
- image_b64 = image_b64,
1168
- image_mime = if (!is.null(image_mime)) image_mime else "image/png")
1169
 
1170
  values$is_typing <- FALSE
1171
  model_short <- gsub(".*/([^:]+):.*", "\\1", model_id)
1172
  add_message("assistant", response, model_used = if (token_exists) model_short else NULL)
1173
 
1174
- # Clear all pending attachments
1175
  values$pending_file_content <- NULL
1176
  values$pending_file_name <- NULL
1177
- values$pending_image_b64 <- NULL
1178
- values$pending_image_mime <- NULL
1179
- values$pending_image_thumb <- NULL
1180
  }
1181
 
1182
  # ---- Handle chat file upload ----
@@ -1186,107 +1061,42 @@ server <- function(input, output, session) {
1186
  file_name <- input$chat_file_upload$name
1187
  ext <- tolower(tools::file_ext(file_name))
1188
 
1189
- # Reset previous pending files
1190
- values$pending_file_content <- NULL
1191
- values$pending_file_name <- NULL
1192
- values$pending_image_b64 <- NULL
1193
- values$pending_image_mime <- NULL
1194
- values$pending_image_thumb <- NULL
1195
-
1196
  tryCatch({
1197
- if (ext %in% c("png", "jpg", "jpeg", "gif", "webp", "bmp")) {
1198
- # ── IMAGE: read as base64, build data URI thumbnail ──
1199
- mime_map <- c(png = "image/png", jpg = "image/jpeg", jpeg = "image/jpeg",
1200
- gif = "image/gif", webp = "image/webp", bmp = "image/bmp")
1201
- mime_type <- unname(mime_map[ext])
1202
- if (is.na(mime_type)) mime_type <- "image/png"
1203
-
1204
- raw_bytes <- readBin(file_path, "raw", file.info(file_path)$size)
1205
- b64_string <- base64enc::base64encode(raw_bytes)
1206
- data_uri <- paste0("data:", mime_type, ";base64,", b64_string)
1207
-
1208
- values$pending_image_b64 <- b64_string
1209
- values$pending_image_mime <- mime_type
1210
- values$pending_image_thumb <- data_uri
1211
- values$pending_file_name <- file_name
1212
-
1213
- showNotification(paste0("Image ready: ", file_name), type = "message")
1214
-
1215
- } else if (ext %in% c("csv", "txt", "tsv")) {
1216
- # ── TEXT files: read lines ──
1217
- file_content <- paste(readLines(file_path, n = 200), collapse = "\n")
1218
- values$pending_file_content <- file_content
1219
- values$pending_file_name <- file_name
1220
-
1221
- } else if (ext == "xlsx") {
1222
- # ── EXCEL: read with readxl if available ──
1223
- if (requireNamespace("readxl", quietly = TRUE)) {
1224
- df <- readxl::read_excel(file_path)
1225
- file_content <- paste(capture.output(print(head(df, 20))), collapse = "\n")
1226
- values$pending_file_content <- paste0("[Excel: ", file_name, "]\n", file_content)
1227
- } else {
1228
- values$pending_file_content <- paste0("[Excel file: ", file_name,
1229
- " - install readxl to parse content]")
1230
- }
1231
- values$pending_file_name <- file_name
1232
-
1233
- } else if (ext == "pdf") {
1234
- # ── PDF: extract text with pdftools if available ──
1235
- if (requireNamespace("pdftools", quietly = TRUE)) {
1236
- txt <- pdftools::pdf_text(file_path)
1237
- file_content <- substr(paste(txt, collapse = "\n"), 1, 3000)
1238
- values$pending_file_content <- paste0("[PDF: ", file_name, "]\n", file_content)
1239
- } else {
1240
- values$pending_file_content <- paste0("[PDF file: ", file_name,
1241
- " - install pdftools to parse content]")
1242
- }
1243
- values$pending_file_name <- file_name
1244
-
1245
  } else {
1246
- values$pending_file_content <- paste0("[File: ", file_name, " (",
1247
- round(file.info(file_path)$size / 1024, 1), " KB)]")
1248
- values$pending_file_name <- file_name
1249
  }
1250
 
 
 
1251
  }, error = function(e) {
1252
  showNotification(paste("Could not read file:", e$message), type = "warning")
1253
  })
1254
  })
1255
 
1256
- # ---- Clear chat file / image ----
1257
  observeEvent(input$clear_chat_file, {
1258
  values$pending_file_content <- NULL
1259
  values$pending_file_name <- NULL
1260
- values$pending_image_b64 <- NULL
1261
- values$pending_image_mime <- NULL
1262
- values$pending_image_thumb <- NULL
1263
  })
1264
 
1265
  # ---- Send chat ----
1266
  observeEvent(input$send_chat, {
1267
- user_text <- trimws(input$chat_input)
1268
  file_content <- isolate(values$pending_file_content)
1269
  file_name <- isolate(values$pending_file_name)
1270
- image_b64 <- isolate(values$pending_image_b64)
1271
- image_mime <- isolate(values$pending_image_mime)
1272
- image_thumb <- isolate(values$pending_image_thumb)
1273
- img_name <- isolate(values$pending_file_name) # same field used for images
1274
 
1275
- has_anything <- nchar(user_text) > 0 || !is.null(file_content) || !is.null(image_b64)
1276
- if (!has_anything) return()
1277
 
1278
  updateTextAreaInput(session, "chat_input", value = "")
 
1279
  shinyjs::runjs("
1280
  document.getElementById('chat_file_preview').style.display = 'none';
1281
  document.getElementById('chat_file_preview').innerHTML = '';
1282
  ")
1283
 
1284
- process_message(user_text,
1285
- file_content = file_content,
1286
- file_name = file_name,
1287
- image_b64 = image_b64,
1288
- image_mime = image_mime,
1289
- image_thumb = image_thumb)
1290
  })
1291
 
1292
  observeEvent(input$quick_q, { req(input$quick_q); process_message(input$quick_q) })
@@ -1306,7 +1116,7 @@ server <- function(input, output, session) {
1306
  "I'm using rule-based responses. Set **HF_API_TOKEN** in Space secrets to enable AI models."
1307
  }
1308
  add_message("assistant", paste0(
1309
- "\U0001f44b Hello! I'm your QTL analysis assistant.\n\n",
1310
  mode_msg,
1311
  "\n\n**I can help you with:**\n",
1312
  "\u2022 **What is PVE?** - Understand variance explained\n",
@@ -1327,21 +1137,6 @@ server <- function(input, output, session) {
1327
  elems <- lapply(messages, function(msg) {
1328
  content_html <- HTML(gsub("\n", "<br>", htmltools::htmlEscape(msg$content)))
1329
 
1330
- # Render image thumbnail inside user bubble if present
1331
- image_tag <- if (!is.null(msg$image_thumb)) {
1332
- tags$div(
1333
- style = "margin-top:8px;",
1334
- tags$img(
1335
- src = msg$image_thumb,
1336
- alt = if (!is.null(msg$image_name)) msg$image_name else "uploaded image",
1337
- style = paste0("max-width:100%; max-height:200px; border-radius:8px;",
1338
- "border:1px solid rgba(255,255,255,0.2); display:block;")
1339
- ),
1340
- if (!is.null(msg$image_name))
1341
- tags$div(style = "font-size:10px; opacity:0.7; margin-top:3px;", msg$image_name)
1342
- )
1343
- } else NULL
1344
-
1345
  meta_content <- tagList(
1346
  span(msg$time),
1347
  if (!is.null(msg$model) && msg$role == "assistant")
@@ -1349,9 +1144,7 @@ server <- function(input, output, session) {
1349
  )
1350
 
1351
  div(class = paste("chat-msg", msg$role),
1352
- div(class = "chat-bubble",
1353
- content_html,
1354
- image_tag),
1355
  div(class = "chat-meta", meta_content))
1356
  })
1357
 
@@ -2084,5 +1877,3 @@ server <- function(input, output, session) {
2084
  # ============================================================
2085
  # RUN APP
2086
  # ============================================================
2087
-
2088
- 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
  )
 
904
  tags$i(class = "fas fa-paperclip"),
905
  " Attach file",
906
  fileInput("chat_file_upload", label = NULL,
907
+ accept = c(".csv", ".txt", ".tsv", ".xlsx", ".pdf"),
908
  buttonLabel = "",
909
  placeholder = "",
910
  width = "0px")
 
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
 
 
1877
  # ============================================================
1878
  # RUN APP
1879
  # ============================================================