s
This commit is contained in:
1 parent
8b54b0a2c4
commit
0d3e076115
21 files changed
+1313
No files matched your search
@@ -0,0 +1,34 @@
|
||||
plugins {
|
||||
id("com.android.application")
|
||||
id("org.jetbrains.kotlin.plugin.compose")
|
||||
}
|
||||
|
||||
android {
|
||||
namespace = "dev.alvin.litellmdashboard"
|
||||
compileSdk = 37
|
||||
|
||||
defaultConfig {
|
||||
applicationId = "dev.alvin.litellmdashboard"
|
||||
minSdk = 26
|
||||
targetSdk = 35
|
||||
versionCode = 1
|
||||
versionName = "1.0.0"
|
||||
}
|
||||
buildFeatures { compose = true }
|
||||
compileOptions {
|
||||
sourceCompatibility = JavaVersion.VERSION_17
|
||||
targetCompatibility = JavaVersion.VERSION_17
|
||||
}
|
||||
packaging { resources.excludes += "/META-INF/{AL2.0,LGPL2.1}" }
|
||||
}
|
||||
|
||||
dependencies {
|
||||
val composeBom = platform("androidx.compose:compose-bom:2026.09.00")
|
||||
implementation(composeBom)
|
||||
implementation("androidx.activity:activity-compose:1.11.0")
|
||||
implementation("androidx.compose.ui:ui")
|
||||
implementation("androidx.compose.ui:ui-tooling-preview")
|
||||
implementation("androidx.compose.foundation:foundation")
|
||||
implementation("androidx.compose.material3:material3")
|
||||
debugImplementation("androidx.compose.ui:ui-tooling")
|
||||
}
|
||||
@@ -0,0 +1,16 @@
|
||||
<?xml version="1.0" encoding="utf-8"?>
|
||||
<manifest xmlns:android="http://schemas.android.com/apk/res/android">
|
||||
<uses-permission android:name="android.permission.INTERNET" />
|
||||
<application
|
||||
android:allowBackup="false"
|
||||
android:usesCleartextTraffic="true"
|
||||
android:label="LiteLLM Dashboard"
|
||||
android:theme="@android:style/Theme.Material.Light.NoActionBar">
|
||||
<activity android:name=".MainActivity" android:exported="true" android:windowSoftInputMode="adjustResize">
|
||||
<intent-filter>
|
||||
<action android:name="android.intent.action.MAIN" />
|
||||
<category android:name="android.intent.category.LAUNCHER" />
|
||||
</intent-filter>
|
||||
</activity>
|
||||
</application>
|
||||
</manifest>
|
||||
@@ -0,0 +1,46 @@
|
||||
package dev.alvin.litellmdashboard
|
||||
|
||||
import android.content.Context
|
||||
import android.security.keystore.KeyGenParameterSpec
|
||||
import android.security.keystore.KeyProperties
|
||||
import android.util.Base64
|
||||
import java.security.KeyStore
|
||||
import javax.crypto.Cipher
|
||||
import javax.crypto.KeyGenerator
|
||||
import javax.crypto.SecretKey
|
||||
import javax.crypto.spec.GCMParameterSpec
|
||||
|
||||
class ConnectionStore(context: Context) {
|
||||
private val prefs = context.getSharedPreferences("connection", Context.MODE_PRIVATE)
|
||||
private val alias = "litellm_dashboard_key"
|
||||
|
||||
private fun secretKey(): SecretKey {
|
||||
val store = KeyStore.getInstance("AndroidKeyStore").apply { load(null) }
|
||||
(store.getKey(alias, null) as? SecretKey)?.let { return it }
|
||||
return KeyGenerator.getInstance(KeyProperties.KEY_ALGORITHM_AES, "AndroidKeyStore").apply {
|
||||
init(KeyGenParameterSpec.Builder(alias, KeyProperties.PURPOSE_ENCRYPT or KeyProperties.PURPOSE_DECRYPT)
|
||||
.setBlockModes(KeyProperties.BLOCK_MODE_GCM)
|
||||
.setEncryptionPaddings(KeyProperties.ENCRYPTION_PADDING_NONE)
|
||||
.setKeySize(256)
|
||||
.build())
|
||||
}.generateKey()
|
||||
}
|
||||
|
||||
fun save(connection: Connection) {
|
||||
val cipher = Cipher.getInstance("AES/GCM/NoPadding").apply { init(Cipher.ENCRYPT_MODE, secretKey()) }
|
||||
val encrypted = cipher.doFinal(connection.apiKey.toByteArray(Charsets.UTF_8))
|
||||
prefs.edit().putString("url", connection.baseUrl)
|
||||
.putString("key", Base64.encodeToString(encrypted, Base64.NO_WRAP))
|
||||
.putString("iv", Base64.encodeToString(cipher.iv, Base64.NO_WRAP)).apply()
|
||||
}
|
||||
|
||||
fun load(): Connection? = try {
|
||||
val url = prefs.getString("url", null) ?: return null
|
||||
val encrypted = Base64.decode(prefs.getString("key", null), Base64.NO_WRAP)
|
||||
val iv = Base64.decode(prefs.getString("iv", null), Base64.NO_WRAP)
|
||||
val cipher = Cipher.getInstance("AES/GCM/NoPadding").apply { init(Cipher.DECRYPT_MODE, secretKey(), GCMParameterSpec(128, iv)) }
|
||||
Connection(url, String(cipher.doFinal(encrypted), Charsets.UTF_8))
|
||||
} catch (_: Exception) { null }
|
||||
|
||||
fun clear() { prefs.edit().clear().apply() }
|
||||
}
|
||||
@@ -0,0 +1,195 @@
|
||||
package dev.alvin.litellmdashboard
|
||||
|
||||
import org.json.JSONArray
|
||||
import org.json.JSONObject
|
||||
import java.net.HttpURLConnection
|
||||
import java.net.URI
|
||||
import java.net.URL
|
||||
import java.time.LocalDate
|
||||
|
||||
data class Connection(val baseUrl: String, val apiKey: String)
|
||||
data class ModelItem(val name: String, val provider: String, val id: String, val mode: String, val context: String)
|
||||
data class KeyItem(val alias: String, val token: String, val owner: String, val team: String, val spend: Double?, val budget: Double?, val blocked: Boolean)
|
||||
data class TeamItem(val name: String, val id: String, val spend: Double?, val budget: Double?, val members: Int?)
|
||||
data class LogItem(val id: String, val model: String, val time: String, val status: String, val spend: Double?, val tokens: Int?, val team: String)
|
||||
data class Overview(val spend: Double?, val requests: Long?, val successful: Long?, val daily: List<Pair<String, Double>>)
|
||||
data class Page<T>(val items: List<T>, val total: Int, val page: Int)
|
||||
|
||||
class ApiException(val status: Int, message: String) : Exception(message)
|
||||
|
||||
class LiteLlmApi(private val connection: Connection) {
|
||||
companion object {
|
||||
fun normalizeUrl(input: String): String {
|
||||
val raw = input.trim().trimEnd('/')
|
||||
val uri = try { URI(raw) } catch (_: Exception) { throw IllegalArgumentException("Enter a valid proxy URL") }
|
||||
val host = uri.host?.lowercase() ?: throw IllegalArgumentException("Enter a full URL such as https://proxy.example.com")
|
||||
if (uri.userInfo != null || uri.query != null || uri.fragment != null || uri.path.orEmpty().contains("..")) throw IllegalArgumentException("Use a proxy base URL without credentials, query, or fragment")
|
||||
if (uri.scheme != "https" && uri.scheme != "http") throw IllegalArgumentException("Only HTTPS and local HTTP are supported")
|
||||
if (uri.scheme == "http" && host != "localhost" && host != "127.0.0.1" && host != "10.0.2.2" && !host.startsWith("192.168.") && !host.startsWith("10.") && !Regex("172\\.(1[6-9]|2[0-9]|3[01])\\..*").matches(host)) {
|
||||
throw IllegalArgumentException("Use HTTPS for public proxy addresses")
|
||||
}
|
||||
return raw
|
||||
}
|
||||
}
|
||||
|
||||
private fun request(path: String, method: String = "GET", payload: JSONObject? = null): Any {
|
||||
val url = URL(connection.baseUrl + path)
|
||||
val http = (url.openConnection() as HttpURLConnection).apply {
|
||||
requestMethod = method
|
||||
connectTimeout = 10000
|
||||
readTimeout = 15000
|
||||
setRequestProperty("Authorization", "Bearer ${connection.apiKey}")
|
||||
setRequestProperty("Accept", "application/json")
|
||||
if (payload != null) {
|
||||
doOutput = true
|
||||
setRequestProperty("Content-Type", "application/json")
|
||||
}
|
||||
instanceFollowRedirects = false
|
||||
}
|
||||
try {
|
||||
if (payload != null) http.outputStream.use { it.write(payload.toString().toByteArray(Charsets.UTF_8)) }
|
||||
val status = http.responseCode
|
||||
if (status in 300..399) throw ApiException(status, "Proxy redirected this request. Check the base URL.")
|
||||
val body = (if (status in 200..299) http.inputStream else http.errorStream)?.bufferedReader()?.use { it.readText() }.orEmpty()
|
||||
if (status !in 200..299) {
|
||||
val detail = try { JSONObject(body).optJSONObject("error")?.optString("message") ?: JSONObject(body).optString("detail") } catch (_: Exception) { "" }
|
||||
val friendly = when (status) {
|
||||
401 -> "Invalid or expired API key"
|
||||
403 -> "This key cannot access this dashboard section"
|
||||
404 -> "Endpoint unavailable on this LiteLLM version"
|
||||
else -> detail.take(180).ifBlank { "Server returned HTTP $status" }
|
||||
}
|
||||
throw ApiException(status, friendly)
|
||||
}
|
||||
return try {
|
||||
if (body.trimStart().startsWith("[")) JSONArray(body) else JSONObject(body)
|
||||
} catch (_: Exception) { throw ApiException(status, "Server did not return JSON") }
|
||||
} finally { http.disconnect() }
|
||||
}
|
||||
|
||||
private fun get(path: String) = request(path)
|
||||
private fun post(path: String, payload: JSONObject) = request(path, "POST", payload)
|
||||
|
||||
private fun array(raw: Any, vararg fields: String): JSONArray {
|
||||
if (raw is JSONArray) return raw
|
||||
val obj = raw as? JSONObject ?: return JSONArray()
|
||||
for (field in fields) {
|
||||
val value = obj.opt(field)
|
||||
if (value is JSONArray) return value
|
||||
if (value is JSONObject) {
|
||||
for (nested in fields) if (value.opt(nested) is JSONArray) return value.getJSONArray(nested)
|
||||
}
|
||||
}
|
||||
return JSONArray()
|
||||
}
|
||||
|
||||
private fun JSONObject.number(vararg names: String): Double? {
|
||||
for (name in names) if (!isNull(name) && has(name)) {
|
||||
val parsed = opt(name)?.toString()?.toDoubleOrNull()
|
||||
if (parsed != null) return parsed
|
||||
}
|
||||
return null
|
||||
}
|
||||
|
||||
private fun JSONObject.string(vararg names: String): String {
|
||||
for (name in names) {
|
||||
val value = optString(name, "")
|
||||
if (value.isNotBlank() && value != "null") return value
|
||||
}
|
||||
return ""
|
||||
}
|
||||
|
||||
fun test(): String {
|
||||
val raw = try { get("/model/info") } catch (e: ApiException) {
|
||||
if (e.status == 403 || e.status == 404) get("/v1/models") else throw e
|
||||
}
|
||||
return "Connected • ${array(raw, "data", "models").length()} models visible"
|
||||
}
|
||||
|
||||
fun createKey(alias: String, budget: Double?): String {
|
||||
val body = JSONObject().put("key_alias", alias.trim())
|
||||
if (budget != null) body.put("max_budget", budget)
|
||||
val result = post("/key/generate", body) as? JSONObject ?: throw ApiException(200, "Unexpected key response")
|
||||
return result.optString("key").takeIf { it.isNotBlank() } ?: throw ApiException(200, "Key created, but the server did not return its value")
|
||||
}
|
||||
|
||||
fun createTeam(name: String, budget: Double?) {
|
||||
val body = JSONObject().put("team_alias", name.trim())
|
||||
if (budget != null) body.put("max_budget", budget)
|
||||
post("/team/new", body)
|
||||
}
|
||||
|
||||
fun createModel(name: String, providerModel: String, providerKey: String) {
|
||||
val params = JSONObject().put("model", providerModel.trim()).put("api_key", providerKey.trim())
|
||||
post("/model/new", JSONObject().put("model_name", name.trim()).put("litellm_params", params))
|
||||
}
|
||||
|
||||
fun models(): List<ModelItem> {
|
||||
val raw = try { get("/model/info") } catch (e: ApiException) {
|
||||
if (e.status == 403 || e.status == 404) get("/v1/models") else throw e
|
||||
}
|
||||
val rows = array(raw, "data", "models")
|
||||
return (0 until rows.length()).mapNotNull { i ->
|
||||
rows.optJSONObject(i)?.let { row ->
|
||||
val params = row.optJSONObject("litellm_params") ?: JSONObject()
|
||||
val info = row.optJSONObject("model_info") ?: JSONObject()
|
||||
val name = row.string("model_name", "id", "model")
|
||||
ModelItem(name, info.string("litellm_provider", "provider").ifBlank { params.string("model").substringBefore('/', "Unknown") }, info.string("id").ifBlank { row.string("id") }, info.string("mode").ifBlank { "chat" }, info.number("max_tokens", "max_input_tokens")?.toInt()?.toString().orEmpty())
|
||||
}
|
||||
}.filter { it.name.isNotBlank() }.distinctBy { it.name }
|
||||
}
|
||||
|
||||
fun keys(page: Int = 1): Page<KeyItem> {
|
||||
val raw = get("/key/list?page=$page&size=30&return_full_object=true")
|
||||
val rows = array(raw, "keys", "data")
|
||||
val items = (0 until rows.length()).mapNotNull { i ->
|
||||
rows.optJSONObject(i)?.let { row ->
|
||||
KeyItem(row.string("key_alias", "alias").ifBlank { "Untitled key" }, row.string("token", "key"), row.string("user_id"), row.string("team_id"), row.number("spend"), row.number("max_budget"), row.optBoolean("blocked", false))
|
||||
}
|
||||
}
|
||||
val obj = raw as? JSONObject
|
||||
val total = obj?.let { it.optInt("total", it.optInt("total_count", if (items.size == 30) page * 30 + 1 else (page - 1) * 30 + items.size)) } ?: items.size
|
||||
return Page(items, total, page)
|
||||
}
|
||||
|
||||
fun teams(): List<TeamItem> {
|
||||
val rows = array(get("/team/list"), "teams", "data")
|
||||
return (0 until rows.length()).mapNotNull { i ->
|
||||
rows.optJSONObject(i)?.let { row -> TeamItem(row.string("team_alias", "team_name").ifBlank { row.string("team_id") }, row.string("team_id"), row.number("spend"), row.number("max_budget"), row.optJSONArray("members_with_roles")?.length() ?: row.optJSONArray("members")?.length()) }
|
||||
}
|
||||
}
|
||||
|
||||
fun logs(page: Int = 1): Page<LogItem> {
|
||||
val end = LocalDate.now()
|
||||
val start = end.minusDays(30)
|
||||
val query = "/spend/logs/v2?start_date=${start}%2000:00:00&end_date=${end}%2023:59:59&page=$page&page_size=30"
|
||||
val obj = get(query) as? JSONObject ?: JSONObject()
|
||||
val rows = array(obj, "data", "logs")
|
||||
val items = (0 until rows.length()).mapNotNull { i ->
|
||||
rows.optJSONObject(i)?.let { row ->
|
||||
val status = row.string("status", "request_status").ifBlank { if (row.optBoolean("success", true)) "success" else "failed" }
|
||||
LogItem(row.string("request_id", "id"), row.string("model", "model_group"), row.string("startTime", "start_time", "created_at"), status, row.number("spend", "response_cost"), row.number("total_tokens")?.toInt(), row.string("team_id", "team_alias"))
|
||||
}
|
||||
}
|
||||
return Page(items, obj.optInt("total", items.size), page)
|
||||
}
|
||||
|
||||
fun overview(): Overview {
|
||||
val spendRaw = try { get("/global/spend") } catch (e: ApiException) { if (e.status == 403 || e.status == 404) null else throw e }
|
||||
val spend = (spendRaw as? JSONObject)?.number("spend", "total_spend")
|
||||
val activityRaw = try { get("/global/activity") } catch (e: ApiException) { if (e.status == 403 || e.status == 404) null else throw e }
|
||||
val activity = activityRaw as? JSONObject
|
||||
val requests = activity?.number("total_requests", "total_api_requests", "total_requests_count")?.toLong()
|
||||
val successful = activity?.number("successful_requests", "success_count")?.toLong()
|
||||
val dailyRaw = try { get("/global/spend/report?start_date=${LocalDate.now().minusDays(6)}&end_date=${LocalDate.now()}") } catch (_: Exception) { null }
|
||||
val days = array(dailyRaw ?: JSONArray(), "data", "results")
|
||||
val daily = (0 until days.length()).mapNotNull { i ->
|
||||
days.optJSONObject(i)?.let { row ->
|
||||
val date = row.string("group_by_day", "date").take(10)
|
||||
val value = row.number("spend", "total_spend") ?: row.optJSONArray("teams")?.let { teams -> (0 until teams.length()).sumOf { teams.optJSONObject(it)?.number("total_spend") ?: 0.0 } }
|
||||
if (date.isBlank() || value == null) null else date to value
|
||||
}
|
||||
}
|
||||
return Overview(spend, requests, successful, daily)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,437 @@
|
||||
package dev.alvin.litellmdashboard
|
||||
|
||||
import android.os.Bundle
|
||||
import android.view.View
|
||||
import androidx.activity.ComponentActivity
|
||||
import androidx.activity.compose.setContent
|
||||
import androidx.compose.foundation.Canvas
|
||||
import androidx.compose.foundation.background
|
||||
import androidx.compose.foundation.clickable
|
||||
import androidx.compose.foundation.rememberScrollState
|
||||
import androidx.compose.foundation.verticalScroll
|
||||
import androidx.compose.foundation.layout.*
|
||||
import androidx.compose.foundation.lazy.LazyColumn
|
||||
import androidx.compose.foundation.lazy.items
|
||||
import androidx.compose.foundation.shape.RoundedCornerShape
|
||||
import androidx.compose.foundation.text.KeyboardOptions
|
||||
import androidx.compose.foundation.text.selection.SelectionContainer
|
||||
import androidx.compose.material3.*
|
||||
import androidx.compose.runtime.*
|
||||
import androidx.compose.ui.Alignment
|
||||
import androidx.compose.ui.Modifier
|
||||
import androidx.compose.ui.geometry.Offset
|
||||
import androidx.compose.ui.graphics.Color
|
||||
import androidx.compose.ui.graphics.StrokeCap
|
||||
import androidx.compose.ui.text.font.FontWeight
|
||||
import androidx.compose.ui.text.input.KeyboardType
|
||||
import androidx.compose.ui.text.input.PasswordVisualTransformation
|
||||
import androidx.compose.ui.text.style.TextOverflow
|
||||
import androidx.compose.ui.unit.dp
|
||||
import androidx.compose.ui.unit.sp
|
||||
import java.net.ConnectException
|
||||
import java.net.SocketTimeoutException
|
||||
import java.text.NumberFormat
|
||||
import java.util.Locale
|
||||
import java.util.concurrent.Executors
|
||||
|
||||
private val Ink = Color(0xFF141D2B)
|
||||
private val Muted = Color(0xFF66758A)
|
||||
private val Blue = Color(0xFF375BE8)
|
||||
private val Pale = Color(0xFFF4F7FB)
|
||||
private val Green = Color(0xFF13876A)
|
||||
|
||||
private fun usd(value: Double?): String = value?.let { NumberFormat.getCurrencyInstance(Locale.US).format(it) } ?: "—"
|
||||
private fun compact(value: Number?): String = value?.let { NumberFormat.getIntegerInstance(Locale.US).format(it) } ?: "—"
|
||||
private fun readableError(t: Throwable): String = when (t) {
|
||||
is ApiException -> t.message ?: "Request failed"
|
||||
is SocketTimeoutException -> "Connection timed out. Check the proxy address and network."
|
||||
is ConnectException -> "Could not reach the proxy. Check its address and network."
|
||||
else -> t.message?.take(180) ?: "Connection failed"
|
||||
}
|
||||
|
||||
private enum class Screen(val label: String, val icon: String) {
|
||||
OVERVIEW("Overview", "◈"), MODELS("Models", "◇"), KEYS("Keys", "✦"), TEAMS("Teams", "◎"), LOGS("Logs", "≡")
|
||||
}
|
||||
|
||||
class MainActivity : ComponentActivity() {
|
||||
private val worker = Executors.newSingleThreadExecutor()
|
||||
private lateinit var store: ConnectionStore
|
||||
private var connection by mutableStateOf<Connection?>(null)
|
||||
private var screen by mutableStateOf(Screen.OVERVIEW)
|
||||
private var settings by mutableStateOf(false)
|
||||
private var connecting by mutableStateOf(false)
|
||||
private var connectionMessage by mutableStateOf("")
|
||||
private var loading by mutableStateOf(false)
|
||||
private var error by mutableStateOf("")
|
||||
private var overview by mutableStateOf<Overview?>(null)
|
||||
private var models by mutableStateOf<List<ModelItem>>(emptyList())
|
||||
private var keys by mutableStateOf(Page<KeyItem>(emptyList(), 0, 1))
|
||||
private var teams by mutableStateOf<List<TeamItem>>(emptyList())
|
||||
private var logs by mutableStateOf(Page<LogItem>(emptyList(), 0, 1))
|
||||
private var recentLogsMessage by mutableStateOf("")
|
||||
private var selectedDetail by mutableStateOf<Pair<String, String>?>(null)
|
||||
private var creating by mutableStateOf(false)
|
||||
private var createBusy by mutableStateOf(false)
|
||||
private var actionResult by mutableStateOf<Pair<String, String>?>(null)
|
||||
|
||||
override fun onCreate(savedInstanceState: Bundle?) {
|
||||
super.onCreate(savedInstanceState)
|
||||
window.statusBarColor = android.graphics.Color.rgb(244, 247, 251)
|
||||
window.navigationBarColor = android.graphics.Color.rgb(244, 247, 251)
|
||||
@Suppress("DEPRECATION")
|
||||
window.decorView.systemUiVisibility = View.SYSTEM_UI_FLAG_LIGHT_STATUS_BAR or View.SYSTEM_UI_FLAG_LIGHT_NAVIGATION_BAR
|
||||
store = ConnectionStore(this)
|
||||
connection = store.load()
|
||||
setContent {
|
||||
MaterialTheme(colorScheme = lightColorScheme(primary = Blue, background = Pale, surface = Color.White, onSurface = Ink)) {
|
||||
Surface(Modifier.fillMaxSize(), color = Pale) {
|
||||
val current = connection
|
||||
if (current == null) ConnectionScreen(connecting, connectionMessage, ::connect)
|
||||
else Dashboard(current)
|
||||
}
|
||||
}
|
||||
}
|
||||
if (connection != null) refresh()
|
||||
}
|
||||
|
||||
override fun onDestroy() {
|
||||
super.onDestroy()
|
||||
worker.shutdownNow()
|
||||
}
|
||||
|
||||
private fun connect(url: String, key: String) {
|
||||
val normalized = try { LiteLlmApi.normalizeUrl(url) } catch (e: IllegalArgumentException) { connectionMessage = e.message.orEmpty(); return }
|
||||
if (key.isBlank()) { connectionMessage = "Enter an API key"; return }
|
||||
connecting = true
|
||||
connectionMessage = ""
|
||||
worker.execute {
|
||||
val candidate = Connection(normalized, key.trim())
|
||||
try {
|
||||
val message = LiteLlmApi(candidate).test()
|
||||
store.save(candidate)
|
||||
runOnUiThread { connection = candidate; connectionMessage = message; connecting = false; refresh() }
|
||||
} catch (t: Throwable) { runOnUiThread { connectionMessage = readableError(t); connecting = false } }
|
||||
}
|
||||
}
|
||||
|
||||
private fun refresh(page: Int = 1) {
|
||||
val current = connection ?: return
|
||||
val target = screen
|
||||
loading = true
|
||||
error = ""
|
||||
worker.execute {
|
||||
try {
|
||||
val api = LiteLlmApi(current)
|
||||
when (target) {
|
||||
Screen.OVERVIEW -> {
|
||||
val data = api.overview()
|
||||
var logMessage = ""
|
||||
val recent = try { api.logs(1) } catch (t: Exception) { logMessage = "Request logs unavailable: ${readableError(t)}"; Page(emptyList(), 0, 1) }
|
||||
runOnUiThread { if (connection == current && screen == target) { overview = data; logs = recent; recentLogsMessage = logMessage; loading = false } }
|
||||
}
|
||||
Screen.MODELS -> { val data = api.models(); runOnUiThread { if (connection == current && screen == target) { models = data; loading = false } } }
|
||||
Screen.KEYS -> { val data = api.keys(page); runOnUiThread { if (connection == current && screen == target) { keys = data; loading = false } } }
|
||||
Screen.TEAMS -> { val data = api.teams(); runOnUiThread { if (connection == current && screen == target) { teams = data; loading = false } } }
|
||||
Screen.LOGS -> { val data = api.logs(page); runOnUiThread { if (connection == current && screen == target) { logs = data; loading = false } } }
|
||||
}
|
||||
} catch (t: Throwable) { runOnUiThread { if (connection == current && screen == target) { error = readableError(t); loading = false } } }
|
||||
}
|
||||
}
|
||||
|
||||
private fun create(first: String, second: String, third: String) {
|
||||
val current = connection ?: return
|
||||
val target = screen
|
||||
creating = false
|
||||
createBusy = true
|
||||
worker.execute {
|
||||
try {
|
||||
val api = LiteLlmApi(current)
|
||||
val result = when (target) {
|
||||
Screen.KEYS -> "Copy this key now. LiteLLM shows it only once:\n\n${api.createKey(first, second.toDoubleOrNull())}"
|
||||
Screen.TEAMS -> { api.createTeam(first, second.toDoubleOrNull()); "Team created successfully." }
|
||||
Screen.MODELS -> { api.createModel(first, second, third); "Model added successfully." }
|
||||
else -> ""
|
||||
}
|
||||
runOnUiThread { createBusy = false; actionResult = "Created" to result; refresh() }
|
||||
} catch (t: Throwable) { runOnUiThread { createBusy = false; actionResult = "Could not create" to readableError(t) } }
|
||||
}
|
||||
}
|
||||
|
||||
@Composable
|
||||
private fun Dashboard(current: Connection) {
|
||||
var query by remember(screen) { mutableStateOf("") }
|
||||
Column(Modifier.fillMaxSize()) {
|
||||
Row(Modifier.fillMaxWidth().background(Color.White).padding(horizontal = 20.dp, vertical = 14.dp), verticalAlignment = Alignment.CenterVertically) {
|
||||
Column(Modifier.weight(1f)) {
|
||||
Text("LiteLLM", fontSize = 13.sp, fontWeight = FontWeight.Bold, color = Blue)
|
||||
Text(if (settings) "Settings" else screen.label, fontSize = 25.sp, fontWeight = FontWeight.Bold, color = Ink)
|
||||
}
|
||||
TextButton(onClick = { if (settings) settings = false else { selectedDetail = null; refresh() } }) { Text(if (settings) "Done" else "Refresh") }
|
||||
TextButton(onClick = { settings = !settings; selectedDetail = null }) { Text(if (settings) "×" else "⚙", fontSize = 23.sp) }
|
||||
}
|
||||
if (loading) LinearProgressIndicator(Modifier.fillMaxWidth())
|
||||
if (createBusy) LinearProgressIndicator(Modifier.fillMaxWidth())
|
||||
Column(Modifier.weight(1f)) {
|
||||
if (settings) {
|
||||
SettingsScreen(current, connectionMessage) {
|
||||
store.clear(); connection = null; settings = false; overview = null; models = emptyList(); keys = Page(emptyList(), 0, 1); teams = emptyList(); logs = Page(emptyList(), 0, 1); recentLogsMessage = ""
|
||||
}
|
||||
} else if (selectedDetail != null) {
|
||||
val detail = selectedDetail!!
|
||||
DetailScreen(detail.first, detail.second) { selectedDetail = null }
|
||||
} else {
|
||||
if (screen == Screen.MODELS || screen == Screen.KEYS || screen == Screen.TEAMS || screen == Screen.LOGS) {
|
||||
Row(Modifier.fillMaxWidth().padding(horizontal = 16.dp, vertical = 8.dp), verticalAlignment = Alignment.CenterVertically) {
|
||||
OutlinedTextField(query, { query = it }, label = { Text(if (screen == Screen.KEYS || screen == Screen.LOGS) "Search this page" else "Search ${screen.label.lowercase()}") }, singleLine = true, modifier = Modifier.weight(1f))
|
||||
if (screen != Screen.LOGS) {
|
||||
Spacer(Modifier.width(8.dp))
|
||||
Button(onClick = { creating = true }, enabled = !createBusy) { Text("Add") }
|
||||
}
|
||||
}
|
||||
}
|
||||
if (error.isNotBlank()) ErrorPanel(error) { refresh() }
|
||||
else when (screen) {
|
||||
Screen.OVERVIEW -> OverviewScreen(overview, logs.items, recentLogsMessage, loading) { selectedDetail = "Request" to it }
|
||||
Screen.MODELS -> InventoryScreen(models.filter { it.name.contains(query, true) || it.provider.contains(query, true) }, loading, "No models visible", { it.name }, { it.provider + if (it.context.isNotBlank()) " • ${it.context} tokens" else "" }, { selectedDetail = "Model" to "Name: ${it.name}\nProvider: ${it.provider}\nMode: ${it.mode}\nID: ${it.id.ifBlank { "—" }}\nContext: ${it.context.ifBlank { "—" }}" })
|
||||
Screen.KEYS -> InventoryScreen(keys.items.filter { it.alias.contains(query, true) || it.owner.contains(query, true) || it.team.contains(query, true) }, loading, "No keys visible", { it.alias }, { "${usd(it.spend)} spent • ${if (it.blocked) "Blocked" else "Active"}" }, { selectedDetail = "Key" to "Alias: ${it.alias}\nOwner: ${it.owner.ifBlank { "—" }}\nTeam: ${it.team.ifBlank { "—" }}\nSpend: ${usd(it.spend)}\nBudget: ${usd(it.budget)}\nStatus: ${if (it.blocked) "Blocked" else "Active"}" }, keys, { refresh(it) })
|
||||
Screen.TEAMS -> InventoryScreen(teams.filter { it.name.contains(query, true) || it.id.contains(query, true) }, loading, "No teams visible", { it.name }, { "${usd(it.spend)} spent • ${it.members ?: "—"} members" }, { selectedDetail = "Team" to "Name: ${it.name}\nID: ${it.id}\nSpend: ${usd(it.spend)}\nBudget: ${usd(it.budget)}\nMembers: ${it.members ?: "—"}" })
|
||||
Screen.LOGS -> LogsScreen(logs, query, loading, { refresh(it) }) { selectedDetail = "Request" to logDetail(it) }
|
||||
}
|
||||
}
|
||||
}
|
||||
if (!settings) NavigationBar(containerColor = Color.White) {
|
||||
Screen.entries.forEach { item ->
|
||||
NavigationBarItem(selected = screen == item, onClick = { if (screen != item) { screen = item; selectedDetail = null; refresh() } }, icon = { Text(item.icon, fontSize = 22.sp) }, label = { Text(item.label, fontSize = 10.sp) })
|
||||
}
|
||||
}
|
||||
}
|
||||
if (creating) CreateDialog(screen, { creating = false }, ::create)
|
||||
actionResult?.let { result ->
|
||||
AlertDialog(onDismissRequest = { if (!result.second.startsWith("Copy this key now")) actionResult = null }, title = { Text(result.first) }, text = { SelectionContainer { Text(result.second) } }, confirmButton = { TextButton(onClick = { actionResult = null }) { Text("Done") } })
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@Composable
|
||||
private fun CreateDialog(screen: Screen, dismiss: () -> Unit, submit: (String, String, String) -> Unit) {
|
||||
var first by remember(screen) { mutableStateOf("") }
|
||||
var second by remember(screen) { mutableStateOf("") }
|
||||
var third by remember(screen) { mutableStateOf("") }
|
||||
var validation by remember(screen) { mutableStateOf("") }
|
||||
val nameLabel = if (screen == Screen.MODELS) "Public model name" else if (screen == Screen.KEYS) "Key alias" else "Team name"
|
||||
AlertDialog(
|
||||
onDismissRequest = dismiss,
|
||||
title = { Text("Add ${screen.label.dropLast(1).lowercase()}") },
|
||||
text = {
|
||||
Column(Modifier.verticalScroll(rememberScrollState())) {
|
||||
OutlinedTextField(first, { first = it }, label = { Text(nameLabel) }, singleLine = true)
|
||||
Spacer(Modifier.height(8.dp))
|
||||
if (screen == Screen.MODELS) {
|
||||
OutlinedTextField(second, { second = it }, label = { Text("Provider/model") }, placeholder = { Text("openai/gpt-4o") }, singleLine = true)
|
||||
Spacer(Modifier.height(8.dp))
|
||||
OutlinedTextField(third, { third = it }, label = { Text("Provider API key") }, singleLine = true, visualTransformation = PasswordVisualTransformation())
|
||||
Text("The provider key is sent to your proxy and is not saved on this device.", fontSize = 11.sp, color = Muted)
|
||||
} else {
|
||||
OutlinedTextField(second, { second = it }, label = { Text("Budget in USD (optional)") }, singleLine = true, keyboardOptions = KeyboardOptions(keyboardType = KeyboardType.Decimal))
|
||||
}
|
||||
if (validation.isNotBlank()) Text(validation, color = Color(0xFFC03434), fontSize = 12.sp)
|
||||
}
|
||||
},
|
||||
confirmButton = {
|
||||
TextButton(onClick = {
|
||||
validation = when {
|
||||
first.isBlank() -> "Enter a name"
|
||||
screen == Screen.MODELS && (second.isBlank() || third.isBlank()) -> "Enter the provider model and API key"
|
||||
screen != Screen.MODELS && second.isNotBlank() && (second.toDoubleOrNull() == null || second.toDouble() <= 0.0) -> "Enter a positive budget or leave it blank"
|
||||
else -> ""
|
||||
}
|
||||
if (validation.isBlank()) submit(first, second, third)
|
||||
}) { Text("Create") }
|
||||
},
|
||||
dismissButton = { TextButton(onClick = dismiss) { Text("Cancel") } }
|
||||
)
|
||||
}
|
||||
|
||||
private fun logDetail(log: LogItem): String = "ID: ${log.id.ifBlank { "—" }}\nModel: ${log.model.ifBlank { "—" }}\nStarted: ${log.time.ifBlank { "—" }}\nStatus: ${log.status}\nSpend: ${usd(log.spend)}\nTokens: ${compact(log.tokens)}\nTeam: ${log.team.ifBlank { "—" }}"
|
||||
|
||||
@Composable
|
||||
private fun ConnectionScreen(connecting: Boolean, message: String, onConnect: (String, String) -> Unit) {
|
||||
var url by remember { mutableStateOf("") }
|
||||
var key by remember { mutableStateOf("") }
|
||||
Column(Modifier.fillMaxSize().verticalScroll(rememberScrollState()).padding(24.dp), verticalArrangement = Arrangement.Center) {
|
||||
Box(Modifier.size(60.dp).background(Blue, RoundedCornerShape(18.dp)), contentAlignment = Alignment.Center) { Text("L", color = Color.White, fontWeight = FontWeight.Black, fontSize = 31.sp) }
|
||||
Spacer(Modifier.height(28.dp))
|
||||
Text("Your LiteLLM,\nin your pocket.", fontSize = 32.sp, lineHeight = 38.sp, fontWeight = FontWeight.Bold, color = Ink)
|
||||
Spacer(Modifier.height(12.dp))
|
||||
Text("Connect to your proxy to explore usage, models, keys, teams, and request logs.", color = Muted, lineHeight = 22.sp)
|
||||
Spacer(Modifier.height(30.dp))
|
||||
OutlinedTextField(url, { url = it }, label = { Text("Proxy URL") }, placeholder = { Text("https://proxy.example.com") }, singleLine = true, keyboardOptions = KeyboardOptions(keyboardType = KeyboardType.Uri), modifier = Modifier.fillMaxWidth())
|
||||
Spacer(Modifier.height(10.dp))
|
||||
OutlinedTextField(key, { key = it }, label = { Text("API key") }, singleLine = true, visualTransformation = PasswordVisualTransformation(), modifier = Modifier.fillMaxWidth())
|
||||
Spacer(Modifier.height(8.dp))
|
||||
Text("Your key is encrypted on this device. Use an admin or read-only management key for dashboard access.", fontSize = 12.sp, lineHeight = 17.sp, color = Muted)
|
||||
if (message.isNotBlank()) { Spacer(Modifier.height(12.dp)); Text(message, color = Color(0xFFC03434), fontSize = 13.sp) }
|
||||
Spacer(Modifier.height(24.dp))
|
||||
Button(onClick = { onConnect(url, key) }, enabled = !connecting, modifier = Modifier.fillMaxWidth().height(52.dp)) { Text(if (connecting) "Connecting…" else "Connect to LiteLLM") }
|
||||
}
|
||||
}
|
||||
|
||||
@Composable
|
||||
private fun SectionTitle(title: String, subtitle: String? = null) {
|
||||
Column(Modifier.padding(top = 22.dp, bottom = 10.dp)) {
|
||||
Text(title, color = Ink, fontWeight = FontWeight.Bold, fontSize = 19.sp)
|
||||
if (subtitle != null) Text(subtitle, color = Muted, fontSize = 12.sp)
|
||||
}
|
||||
}
|
||||
|
||||
@Composable
|
||||
private fun MetricCard(label: String, value: String, modifier: Modifier = Modifier) {
|
||||
Card(modifier, colors = CardDefaults.cardColors(containerColor = Color.White), shape = RoundedCornerShape(18.dp)) {
|
||||
Column(Modifier.padding(18.dp)) {
|
||||
Text(label, fontSize = 12.sp, color = Muted)
|
||||
Spacer(Modifier.height(9.dp))
|
||||
Text(value, fontSize = 24.sp, fontWeight = FontWeight.Bold, color = Ink)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@Composable
|
||||
private fun OverviewScreen(overview: Overview?, recent: List<LogItem>, logMessage: String, loading: Boolean, onLog: (String) -> Unit) {
|
||||
LazyColumn(contentPadding = PaddingValues(16.dp), verticalArrangement = Arrangement.spacedBy(12.dp)) {
|
||||
item {
|
||||
Text("Proxy overview", fontSize = 13.sp, color = Muted)
|
||||
Spacer(Modifier.height(12.dp))
|
||||
MetricCard("Total spend", usd(overview?.spend), Modifier.fillMaxWidth())
|
||||
Spacer(Modifier.height(12.dp))
|
||||
Row(horizontalArrangement = Arrangement.spacedBy(12.dp)) {
|
||||
MetricCard("Requests", compact(overview?.requests), Modifier.weight(1f))
|
||||
MetricCard("Successful", compact(overview?.successful), Modifier.weight(1f))
|
||||
}
|
||||
SectionTitle("Last 7 days", "Spend by day")
|
||||
Card(colors = CardDefaults.cardColors(containerColor = Color.White), shape = RoundedCornerShape(18.dp)) {
|
||||
if (overview?.daily.isNullOrEmpty()) Text("No daily spend data available", Modifier.padding(22.dp), color = Muted)
|
||||
else SpendChart(overview!!.daily, Modifier.fillMaxWidth().height(150.dp).padding(22.dp))
|
||||
}
|
||||
SectionTitle("Recent requests")
|
||||
}
|
||||
if (recent.isEmpty() && !loading) item { EmptyPanel(logMessage.ifBlank { "No request logs in the last 30 days" }) }
|
||||
items(recent.take(5)) { log -> LogRow(log) { onLog(logDetail(log)) } }
|
||||
}
|
||||
}
|
||||
|
||||
@Composable
|
||||
private fun SpendChart(values: List<Pair<String, Double>>, modifier: Modifier) {
|
||||
Canvas(modifier) {
|
||||
val max = (values.maxOfOrNull { it.second } ?: 0.0).coerceAtLeast(0.001)
|
||||
val gap = size.width / values.size
|
||||
values.forEachIndexed { i, value ->
|
||||
val x = (i + 0.5f) * gap
|
||||
val barHeight = (value.second / max).toFloat() * size.height
|
||||
drawLine(Blue, Offset(x, size.height), Offset(x, size.height - barHeight), strokeWidth = (gap * 0.45f).coerceAtMost(38.dp.toPx()), cap = StrokeCap.Round)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@Composable
|
||||
private fun <T> InventoryScreen(items: List<T>, loading: Boolean, empty: String, title: (T) -> String, subtitle: (T) -> String, onClick: (T) -> Unit, page: Page<T>? = null, onPage: ((Int) -> Unit)? = null) {
|
||||
if (items.isEmpty() && !loading) { EmptyPanel(empty); return }
|
||||
LazyColumn(contentPadding = PaddingValues(16.dp), verticalArrangement = Arrangement.spacedBy(10.dp)) {
|
||||
items(items) { item ->
|
||||
Card(Modifier.fillMaxWidth().clickable { onClick(item) }, colors = CardDefaults.cardColors(containerColor = Color.White), shape = RoundedCornerShape(16.dp)) {
|
||||
Column(Modifier.padding(18.dp)) {
|
||||
Text(title(item), color = Ink, fontWeight = FontWeight.SemiBold, maxLines = 2, overflow = TextOverflow.Ellipsis)
|
||||
Spacer(Modifier.height(6.dp))
|
||||
Text(subtitle(item), color = Muted, fontSize = 13.sp, maxLines = 2, overflow = TextOverflow.Ellipsis)
|
||||
}
|
||||
}
|
||||
}
|
||||
if (page != null && onPage != null) item {
|
||||
Row(Modifier.fillMaxWidth(), horizontalArrangement = Arrangement.SpaceBetween) {
|
||||
TextButton(onClick = { onPage(page.page - 1) }, enabled = page.page > 1 && !loading) { Text("← Previous") }
|
||||
TextButton(onClick = { onPage(page.page + 1) }, enabled = page.page * 30 < page.total && !loading) { Text("Next →") }
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@Composable
|
||||
private fun LogsScreen(page: Page<LogItem>, query: String, loading: Boolean, onPage: (Int) -> Unit, onClick: (LogItem) -> Unit) {
|
||||
val visible = page.items.filter { it.model.contains(query, true) || it.id.contains(query, true) || it.status.contains(query, true) }
|
||||
if (visible.isEmpty() && !loading) { EmptyPanel(if (query.isBlank()) "No requests in the last 30 days" else "No matching requests on this page"); return }
|
||||
LazyColumn(contentPadding = PaddingValues(16.dp), verticalArrangement = Arrangement.spacedBy(10.dp)) {
|
||||
item { Text("${compact(page.total)} requests • page ${page.page}", color = Muted, fontSize = 12.sp) }
|
||||
items(visible) { log -> LogRow(log) { onClick(log) } }
|
||||
item {
|
||||
Row(Modifier.fillMaxWidth(), horizontalArrangement = Arrangement.SpaceBetween) {
|
||||
TextButton(onClick = { onPage(page.page - 1) }, enabled = page.page > 1 && !loading) { Text("← Previous") }
|
||||
TextButton(onClick = { onPage(page.page + 1) }, enabled = page.page * 30 < page.total && !loading) { Text("Next →") }
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@Composable
|
||||
private fun LogRow(log: LogItem, onClick: () -> Unit) {
|
||||
Card(Modifier.fillMaxWidth().clickable(onClick = onClick), colors = CardDefaults.cardColors(containerColor = Color.White), shape = RoundedCornerShape(16.dp)) {
|
||||
Row(Modifier.padding(16.dp), verticalAlignment = Alignment.CenterVertically) {
|
||||
Box(Modifier.size(9.dp).background(if (log.status.contains("success", true)) Green else Color(0xFFE39931), RoundedCornerShape(50)))
|
||||
Spacer(Modifier.width(12.dp))
|
||||
Column(Modifier.weight(1f)) {
|
||||
Text(log.model.ifBlank { "Unknown model" }, color = Ink, fontWeight = FontWeight.SemiBold, maxLines = 1, overflow = TextOverflow.Ellipsis)
|
||||
Text(log.time.take(19).replace('T', ' '), color = Muted, fontSize = 12.sp)
|
||||
}
|
||||
Column(horizontalAlignment = Alignment.End) {
|
||||
Text(usd(log.spend), color = Ink, fontWeight = FontWeight.Medium)
|
||||
Text("${compact(log.tokens)} tokens", color = Muted, fontSize = 11.sp)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@Composable
|
||||
private fun EmptyPanel(message: String) {
|
||||
Box(Modifier.fillMaxWidth().padding(24.dp).background(Color.White, RoundedCornerShape(18.dp)).padding(28.dp), contentAlignment = Alignment.Center) { Text(message, color = Muted) }
|
||||
}
|
||||
|
||||
@Composable
|
||||
private fun ErrorPanel(message: String, retry: () -> Unit) {
|
||||
Column(Modifier.fillMaxWidth().padding(16.dp).background(Color.White, RoundedCornerShape(18.dp)).padding(20.dp)) {
|
||||
Text("Could not load this section", color = Ink, fontWeight = FontWeight.Bold)
|
||||
Spacer(Modifier.height(6.dp))
|
||||
Text(message, color = Muted)
|
||||
Spacer(Modifier.height(8.dp))
|
||||
TextButton(onClick = retry) { Text("Try again") }
|
||||
}
|
||||
}
|
||||
|
||||
@Composable
|
||||
private fun DetailScreen(title: String, content: String, back: () -> Unit) {
|
||||
Column(Modifier.fillMaxSize().padding(20.dp)) {
|
||||
TextButton(onClick = back) { Text("← Back") }
|
||||
Spacer(Modifier.height(8.dp))
|
||||
Text(title, color = Ink, fontSize = 24.sp, fontWeight = FontWeight.Bold)
|
||||
Spacer(Modifier.height(18.dp))
|
||||
Card(colors = CardDefaults.cardColors(containerColor = Color.White), shape = RoundedCornerShape(18.dp)) { Text(content, Modifier.fillMaxWidth().padding(20.dp), color = Ink, lineHeight = 26.sp) }
|
||||
}
|
||||
}
|
||||
|
||||
@Composable
|
||||
private fun SettingsScreen(connection: Connection, message: String, disconnect: () -> Unit) {
|
||||
Column(Modifier.fillMaxSize().padding(20.dp)) {
|
||||
SectionTitle("Connection")
|
||||
Card(colors = CardDefaults.cardColors(containerColor = Color.White), shape = RoundedCornerShape(18.dp)) {
|
||||
Column(Modifier.fillMaxWidth().padding(20.dp)) {
|
||||
Text("Proxy address", fontSize = 12.sp, color = Muted)
|
||||
Text(connection.baseUrl, color = Ink, fontWeight = FontWeight.SemiBold)
|
||||
Spacer(Modifier.height(14.dp))
|
||||
Text("API key", fontSize = 12.sp, color = Muted)
|
||||
Text("Saved securely on this device", color = Ink)
|
||||
if (message.isNotBlank()) { Spacer(Modifier.height(12.dp)); Text(message, color = Green, fontSize = 12.sp) }
|
||||
}
|
||||
}
|
||||
Spacer(Modifier.height(24.dp))
|
||||
OutlinedButton(onClick = disconnect, modifier = Modifier.fillMaxWidth()) { Text("Disconnect and remove key") }
|
||||
Spacer(Modifier.height(18.dp))
|
||||
Text("LiteLLM Dashboard 1.0.0", color = Muted, fontSize = 12.sp)
|
||||
}
|
||||
}
|
||||
Reference in new issue
Block a user