s
This commit is contained in:
1 parent
8b54b0a2c4
commit
0d3e076115
21 files changed
+1313
No files matched your search
+10
@@ -0,0 +1,10 @@
|
|||||||
|
*.iml
|
||||||
|
.gradle/
|
||||||
|
.kotlin/
|
||||||
|
local.properties
|
||||||
|
**/build/
|
||||||
|
.idea/workspace.xml
|
||||||
|
.idea/caches/
|
||||||
|
captures/
|
||||||
|
*.apk
|
||||||
|
connection.txt
|
||||||
Generated
+18
@@ -0,0 +1,18 @@
|
|||||||
|
<?xml version="1.0" encoding="UTF-8"?>
|
||||||
|
<project version="4">
|
||||||
|
<component name="DeviceTable">
|
||||||
|
<option name="columnSorters">
|
||||||
|
<list>
|
||||||
|
<ColumnSorterState>
|
||||||
|
<option name="column" value="Name" />
|
||||||
|
<option name="order" value="ASCENDING" />
|
||||||
|
</ColumnSorterState>
|
||||||
|
</list>
|
||||||
|
</option>
|
||||||
|
<option name="groupByAttributes">
|
||||||
|
<list>
|
||||||
|
<option value="Type" />
|
||||||
|
</list>
|
||||||
|
</option>
|
||||||
|
</component>
|
||||||
|
</project>
|
||||||
Generated
+11
@@ -0,0 +1,11 @@
|
|||||||
|
<?xml version="1.0" encoding="UTF-8"?>
|
||||||
|
<project version="4">
|
||||||
|
<component name="GradleSettings">
|
||||||
|
<option name="linkedExternalProjectsSettings">
|
||||||
|
<GradleProjectSettings>
|
||||||
|
<option name="testRunner" value="CHOOSE_PER_TEST" />
|
||||||
|
<option name="externalProjectPath" value="$PROJECT_DIR$" />
|
||||||
|
</GradleProjectSettings>
|
||||||
|
</option>
|
||||||
|
</component>
|
||||||
|
</project>
|
||||||
Generated
+1
@@ -1,5 +1,6 @@
|
|||||||
<?xml version="1.0" encoding="UTF-8"?>
|
<?xml version="1.0" encoding="UTF-8"?>
|
||||||
<project version="4">
|
<project version="4">
|
||||||
|
<component name="ExternalStorageConfigurationManager" enabled="true" />
|
||||||
<component name="ProjectRootManager" version="2" languageLevel="JDK_25" default="true" project-jdk-name="jbr-25" project-jdk-type="JavaSDK">
|
<component name="ProjectRootManager" version="2" languageLevel="JDK_25" default="true" project-jdk-name="jbr-25" project-jdk-type="JavaSDK">
|
||||||
<output url="file://$PROJECT_DIR$/out" />
|
<output url="file://$PROJECT_DIR$/out" />
|
||||||
</component>
|
</component>
|
||||||
|
|||||||
Generated
+6
@@ -0,0 +1,6 @@
|
|||||||
|
<?xml version="1.0" encoding="UTF-8"?>
|
||||||
|
<project version="4">
|
||||||
|
<component name="VcsDirectoryMappings">
|
||||||
|
<mapping directory="$PROJECT_DIR$" vcs="Git" />
|
||||||
|
</component>
|
||||||
|
</project>
|
||||||
@@ -0,0 +1,35 @@
|
|||||||
|
# LiteLLM Android dashboard: research and build plan
|
||||||
|
|
||||||
|
## Research (19 November 2026)
|
||||||
|
|
||||||
|
- LiteLLM's proxy exposes bearer authenticated management APIs. The current API reference lists `/model/info`, `/key/list`, `/team/list`, `/global/spend`, `/global/activity`, and `/spend/logs/v2`. Usage logs use page based pagination and date filters. [API reference](https://docs.litellm.ai/api-reference), [spend tracking](https://docs.litellm.ai/docs/proxy/cost_tracking).
|
||||||
|
- A LiteLLM admin UI requires a proxy with a database and a master key. Key and management access depends on the caller's role and allowed routes. The mobile app should surface 401/403 responses instead of assuming admin rights. [UI setup](https://docs.litellm.ai/docs/proxy/ui), [virtual keys](https://docs.litellm.ai/docs/proxy/virtual_keys).
|
||||||
|
- `/model/info` returns configured models with masked provider credentials. The app must not display or persist provider secrets. [Model management](https://docs.litellm.ai/docs/proxy/model_management).
|
||||||
|
- Android recommends Compose BOM and the Kotlin Compose compiler plugin for a native Compose app. [Compose BOM](https://developer.android.com/develop/ui/compose/bom), [compiler setup](https://developer.android.com/develop/ui/compose/setup-compose-dependencies-and-compiler).
|
||||||
|
|
||||||
|
## Product scope
|
||||||
|
|
||||||
|
1. Connection screen: proxy URL and API key, test connection, secure credential storage, clear connection.
|
||||||
|
2. Overview: total spend, activity summary, recent requests, and refresh.
|
||||||
|
3. Models: searchable list and model details.
|
||||||
|
4. Keys and teams: searchable management inventory, spending and budget information where returned by the proxy, plus admin creation flows.
|
||||||
|
5. Logs: paginated recent request list with status, model, tokens, cost, and detail view.
|
||||||
|
6. Model creation for an authorized admin; settings with server identity, connection status, and sign out. Every screen has loading, empty, and actionable error states.
|
||||||
|
|
||||||
|
## Implementation sequence
|
||||||
|
|
||||||
|
1. Scaffold a native single-activity Kotlin/Jetpack Compose Android project.
|
||||||
|
2. Add a small HTTP repository with strict URL normalization, bearer auth, timeouts, and tolerant parsing of LiteLLM response variants.
|
||||||
|
3. Build navigation and the core dashboard screens, then connect them to live proxy data.
|
||||||
|
4. Add secure local storage for the API key, accessible labels, and Android network configuration.
|
||||||
|
5. Build a debug APK, install and exercise it on the emulator via adb; fix issues found.
|
||||||
|
|
||||||
|
## Acceptance checks
|
||||||
|
|
||||||
|
- Launches without a configured proxy and explains how to connect.
|
||||||
|
- Rejects malformed server URLs; connects to an HTTPS server (or explicitly configured local HTTP server) and handles invalid credentials.
|
||||||
|
- Renders real data from authorized endpoints and keeps empty, forbidden, and server error states distinct.
|
||||||
|
- Never logs or exposes the saved key in UI, app backups, or source.
|
||||||
|
- Compiles and launches on the available Android emulator.
|
||||||
|
|
||||||
|
The repository started without application source. No proxy URL or API key was supplied, so live server data and privileged write actions cannot be verified against the user's deployment. Destructive management actions are outside the initial scope.
|
||||||
+51
@@ -0,0 +1,51 @@
|
|||||||
|
# LiteLLM Android dashboard progress
|
||||||
|
|
||||||
|
Last reviewed: 19 November 2026
|
||||||
|
|
||||||
|
This file tracks the Android app in this repository. A checked item means the feature exists in source; the verification notes say how far it has been tested. The current build is a functional core dashboard, not a complete mobile replacement for every page in LiteLLM's web admin UI.
|
||||||
|
|
||||||
|
## Completed
|
||||||
|
|
||||||
|
- [x] Researched LiteLLM proxy management and spend endpoints and Android Compose setup; recorded the original scope and acceptance checks in [PLAN.md](PLAN.md).
|
||||||
|
- [x] Created a native Kotlin/Jetpack Compose Android project with Gradle wrapper, Android manifest, and build instructions in [README.md](README.md).
|
||||||
|
- [x] Added a connection screen with proxy URL validation, bearer-key authentication, connection test, timeouts, and readable network/authentication errors.
|
||||||
|
- [x] Encrypted the saved API key with Android Keystore, disabled app backup, and added disconnect/key removal.
|
||||||
|
- [x] Built bottom navigation and settings, with loading, empty, retry, and section-specific error views.
|
||||||
|
- [x] Added an overview showing total spend, request counts, a seven-day spend chart, and recent requests where the proxy permits them.
|
||||||
|
- [x] Added searchable model inventory and model detail views. The app falls back to `/v1/models` if `/model/info` is unavailable or forbidden.
|
||||||
|
- [x] Added key inventory, details, and page navigation. Key search filters the currently loaded page.
|
||||||
|
- [x] Added team inventory and details.
|
||||||
|
- [x] Added a 30-day spend-log list, details, and page navigation. Log search filters the currently loaded page.
|
||||||
|
- [x] Added authorized creation forms for models, virtual keys, and teams. A generated virtual key is shown once and is not persisted by the app.
|
||||||
|
- [x] Added a local LiteLLM-shaped test proxy at [tools/mock_proxy.py](tools/mock_proxy.py).
|
||||||
|
- [x] Built a debug APK with `./gradlew.bat :app:assembleDebug` and installed/launched it on `emulator-5554` through adb.
|
||||||
|
- [x] Exercised connection, overview, inventories, log pagination, saved-connection restart, and all three creation flows against the local test proxy. Fixed a short-list navigation layout issue found during emulator review. The final APK launched after rebuilding.
|
||||||
|
|
||||||
|
## Needs work or verification
|
||||||
|
|
||||||
|
- [ ] Connect to a real LiteLLM deployment and verify the response shapes, permissions, and create flows across the deployment's actual LiteLLM version. No live proxy URL or credential has been provided, so the app has only been integration-tested against the local fixture.
|
||||||
|
- [ ] Confirm the overview's `/global/spend` and `/global/activity` metrics against real admin and restricted keys. Forbidden metrics currently appear as unavailable values; make their reason explicit on the overview.
|
||||||
|
- [ ] Verify connection failure paths on-device with invalid keys, forbidden endpoints, expired credentials, TLS/certificate failures, and a proxy mounted under a URL path. These states have code paths but were not all exercised on the emulator.
|
||||||
|
- [ ] Add automated tests for URL validation, API response parsing, authentication/error mapping, and creation payloads. The repository currently has no automated test suite or CI workflow.
|
||||||
|
- [ ] Improve large-installation browsing: server-side key search, more reliable total/page handling across LiteLLM versions, and pagination or filtering for teams and models where needed. Current key and log search works only within a page.
|
||||||
|
- [ ] Improve the chart with date/value labels and clarify the time range of overview totals. The current bar chart communicates magnitude but has no axis or per-day labels.
|
||||||
|
- [ ] Review accessibility on a range of screen sizes, font scales, keyboard navigation, and screen-reader settings. Standard Compose labels are present, but a full accessibility pass has not been done.
|
||||||
|
- [ ] Produce a signed release build and document distribution. The existing APK is a debug build only.
|
||||||
|
|
||||||
|
## Not started
|
||||||
|
|
||||||
|
- [ ] Edit, block/unblock, rotate, or revoke virtual keys; edit or delete models and teams. These management operations are not in the current UI.
|
||||||
|
- [ ] User, organization, project, budget, tag, guardrail, credential, and access-group management.
|
||||||
|
- [ ] Usage breakdowns and filters by model, provider, team, user, key, or date range; export/report workflows.
|
||||||
|
- [ ] Advanced log filters, server-side search, full request traces, and prompt/response inspection where LiteLLM has been configured to store them.
|
||||||
|
- [ ] Alerts, push notifications, widgets, or background synchronization.
|
||||||
|
- [ ] Multiple saved proxy profiles and account switching.
|
||||||
|
- [ ] Play Store packaging, release signing, crash reporting, and production telemetry.
|
||||||
|
|
||||||
|
## Next milestone
|
||||||
|
|
||||||
|
1. Test against a real proxy with a suitably scoped key and record its LiteLLM version and any endpoint differences.
|
||||||
|
2. Fix the API and permission issues uncovered by that test.
|
||||||
|
3. Add automated regression tests for those real response shapes, then build a signed release candidate.
|
||||||
|
|
||||||
|
Update this file whenever a feature is completed or a gap is discovered. Move an item to **Completed** only after implementation; record the verification level separately when it has not been exercised against a live deployment.
|
||||||
@@ -0,0 +1,51 @@
|
|||||||
|
# LiteLLM Dashboard for Android
|
||||||
|
|
||||||
|
A native Android dashboard for a self-hosted LiteLLM proxy. Built with Kotlin and Jetpack Compose.
|
||||||
|
|
||||||
|
See [PROGRESS.md](PROGRESS.md) for completed work, remaining verification, and features not yet started.
|
||||||
|
|
||||||
|
## Features
|
||||||
|
|
||||||
|
- Connect with a proxy URL and bearer API key; the key is encrypted with Android Keystore and excluded from backups.
|
||||||
|
- Overview with total spend, request counts, a daily spend chart, and recent requests.
|
||||||
|
- Searchable model, key, and team inventories with detail views. Key search filters the current page; use page navigation for larger installations.
|
||||||
|
- Recent spend logs with request details and page navigation.
|
||||||
|
- Create models, virtual keys, and teams when the connected key has permission. Newly generated virtual keys are shown once and are not saved by the app.
|
||||||
|
- Explicit loading, empty, authentication, permission, and network error states.
|
||||||
|
|
||||||
|
The app follows the proxy's permissions. An inference-only key may show models but cannot access admin sections. Use an admin key or a management key with appropriate read/write routes. LiteLLM's database-backed management APIs must be enabled for key and team features. Model creation requires `store_model_in_db` on the proxy.
|
||||||
|
|
||||||
|
## Build
|
||||||
|
|
||||||
|
Open the root folder in Android Studio, or run on Windows:
|
||||||
|
|
||||||
|
```powershell
|
||||||
|
./gradlew.bat :app:assembleDebug
|
||||||
|
adb install -r app/build/outputs/apk/debug/app-debug.apk
|
||||||
|
```
|
||||||
|
|
||||||
|
Requires JDK 17+, Android SDK platform 37, and an emulator/device running Android 8.0 or newer. The debug APK is at `app/build/outputs/apk/debug/app-debug.apk`.
|
||||||
|
|
||||||
|
## Connect
|
||||||
|
|
||||||
|
Enter the proxy base URL, for example `https://litellm.example.com`. Public addresses must use HTTPS. HTTP is accepted only for localhost, Android emulator host `10.0.2.2`, and private LAN addresses. Do not append `/ui` or an endpoint path. For a local proxy on the host, use `http://10.0.2.2:4000` from the standard Android emulator.
|
||||||
|
|
||||||
|
The app sends the key only in the `Authorization: Bearer` header. Disconnecting removes the stored connection. LiteLLM versions and deployment settings vary, so unsupported or forbidden endpoints appear as section-specific errors.
|
||||||
|
|
||||||
|
## Local emulator fixture
|
||||||
|
|
||||||
|
The fixture in `tools/mock_proxy.py` exercises the app without a real LiteLLM deployment:
|
||||||
|
|
||||||
|
```powershell
|
||||||
|
python tools/mock_proxy.py
|
||||||
|
adb reverse tcp:8765 tcp:8765
|
||||||
|
```
|
||||||
|
|
||||||
|
Connect to `http://127.0.0.1:8765` with `sk-demo`. The fixture includes models, spend, keys, teams, logs, and creation responses. It is for development only.
|
||||||
|
|
||||||
|
## Sources
|
||||||
|
|
||||||
|
- [LiteLLM proxy API reference](https://docs.litellm.ai/api-reference)
|
||||||
|
- [LiteLLM spend tracking](https://docs.litellm.ai/docs/proxy/cost_tracking)
|
||||||
|
- [LiteLLM model management](https://docs.litellm.ai/docs/proxy/model_management)
|
||||||
|
- [Android Compose BOM](https://developer.android.com/develop/ui/compose/bom)
|
||||||
@@ -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)
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,4 @@
|
|||||||
|
plugins {
|
||||||
|
id("com.android.application") version "9.4.0" apply false
|
||||||
|
id("org.jetbrains.kotlin.plugin.compose") version "2.2.20" apply false
|
||||||
|
}
|
||||||
@@ -0,0 +1,3 @@
|
|||||||
|
org.gradle.jvmargs=-Xmx2048m -Dfile.encoding=UTF-8
|
||||||
|
android.useAndroidX=true
|
||||||
|
org.gradle.parallel=true
|
||||||
Vendored
BIN
Binary file not shown.
+9
@@ -0,0 +1,9 @@
|
|||||||
|
distributionBase=GRADLE_USER_HOME
|
||||||
|
distributionPath=wrapper/dists
|
||||||
|
distributionUrl=https\://services.gradle.org/distributions/gradle-9.6.0-bin.zip
|
||||||
|
networkTimeout=10000
|
||||||
|
retries=0
|
||||||
|
retryBackOffMs=500
|
||||||
|
validateDistributionUrl=true
|
||||||
|
zipStoreBase=GRADLE_USER_HOME
|
||||||
|
zipStorePath=wrapper/dists
|
||||||
@@ -0,0 +1,248 @@
|
|||||||
|
#!/bin/sh
|
||||||
|
|
||||||
|
#
|
||||||
|
# Copyright © 2015 the original authors.
|
||||||
|
#
|
||||||
|
# Licensed under the Apache License, Version 2.0 (the "License");
|
||||||
|
# you may not use this file except in compliance with the License.
|
||||||
|
# You may obtain a copy of the License at
|
||||||
|
#
|
||||||
|
# https://www.apache.org/licenses/LICENSE-2.0
|
||||||
|
#
|
||||||
|
# Unless required by applicable law or agreed to in writing, software
|
||||||
|
# distributed under the License is distributed on an "AS IS" BASIS,
|
||||||
|
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||||
|
# See the License for the specific language governing permissions and
|
||||||
|
# limitations under the License.
|
||||||
|
#
|
||||||
|
# SPDX-License-Identifier: Apache-2.0
|
||||||
|
#
|
||||||
|
|
||||||
|
##############################################################################
|
||||||
|
#
|
||||||
|
# gradlew start up script for POSIX generated by Gradle.
|
||||||
|
#
|
||||||
|
# Important for running:
|
||||||
|
#
|
||||||
|
# (1) You need a POSIX-compliant shell to run this script. If your /bin/sh is
|
||||||
|
# noncompliant, but you have some other compliant shell such as ksh or
|
||||||
|
# bash, then to run this script, type that shell name before the whole
|
||||||
|
# command line, like:
|
||||||
|
#
|
||||||
|
# ksh gradlew
|
||||||
|
#
|
||||||
|
# Busybox and similar reduced shells will NOT work, because this script
|
||||||
|
# requires all of these POSIX shell features:
|
||||||
|
# * functions;
|
||||||
|
# * expansions «$var», «${var}», «${var:-default}», «${var+SET}»,
|
||||||
|
# «${var#prefix}», «${var%suffix}», and «$( cmd )»;
|
||||||
|
# * compound commands having a testable exit status, especially «case»;
|
||||||
|
# * various built-in commands including «command», «set», and «ulimit».
|
||||||
|
#
|
||||||
|
# Important for patching:
|
||||||
|
#
|
||||||
|
# (2) This script targets any POSIX shell, so it avoids extensions provided
|
||||||
|
# by Bash, Ksh, etc; in particular arrays are avoided.
|
||||||
|
#
|
||||||
|
# The "traditional" practice of packing multiple parameters into a
|
||||||
|
# space-separated string is a well documented source of bugs and security
|
||||||
|
# problems, so this is (mostly) avoided, by progressively accumulating
|
||||||
|
# options in "$@", and eventually passing that to Java.
|
||||||
|
#
|
||||||
|
# Where the inherited environment variables (DEFAULT_JVM_OPTS, JAVA_OPTS,
|
||||||
|
# and GRADLE_OPTS) rely on word-splitting, this is performed explicitly;
|
||||||
|
# see the in-line comments for details.
|
||||||
|
#
|
||||||
|
# There are tweaks for specific operating systems such as AIX, CygWin,
|
||||||
|
# Darwin, MinGW, and NonStop.
|
||||||
|
#
|
||||||
|
# (3) This script is generated from the Groovy template
|
||||||
|
# https://github.com/gradle/gradle/blob/3d91ce3b8caaf77ad09f381f43615b715b53f72c/platforms/jvm/plugins-application/src/main/resources/org/gradle/api/internal/plugins/unixStartScript.txt
|
||||||
|
# within the Gradle project.
|
||||||
|
#
|
||||||
|
# You can find Gradle at https://github.com/gradle/gradle/.
|
||||||
|
#
|
||||||
|
##############################################################################
|
||||||
|
|
||||||
|
# Attempt to set APP_HOME
|
||||||
|
|
||||||
|
# Resolve links: $0 may be a link
|
||||||
|
app_path=$0
|
||||||
|
|
||||||
|
# Need this for daisy-chained symlinks.
|
||||||
|
while
|
||||||
|
APP_HOME=${app_path%"${app_path##*/}"} # leaves a trailing /; empty if no leading path
|
||||||
|
[ -h "$app_path" ]
|
||||||
|
do
|
||||||
|
ls=$( ls -ld "$app_path" )
|
||||||
|
link=${ls#*' -> '}
|
||||||
|
case $link in #(
|
||||||
|
/*) app_path=$link ;; #(
|
||||||
|
*) app_path=$APP_HOME$link ;;
|
||||||
|
esac
|
||||||
|
done
|
||||||
|
|
||||||
|
# This is normally unused
|
||||||
|
# shellcheck disable=SC2034
|
||||||
|
APP_BASE_NAME=${0##*/}
|
||||||
|
# Discard cd standard output in case $CDPATH is set (https://github.com/gradle/gradle/issues/25036)
|
||||||
|
APP_HOME=$( cd -P "${APP_HOME:-./}" > /dev/null && printf '%s\n' "$PWD" ) || exit
|
||||||
|
|
||||||
|
# Use the maximum available, or set MAX_FD != -1 to use that value.
|
||||||
|
MAX_FD=maximum
|
||||||
|
|
||||||
|
warn () {
|
||||||
|
echo "$*"
|
||||||
|
} >&2
|
||||||
|
|
||||||
|
die () {
|
||||||
|
echo
|
||||||
|
echo "$*"
|
||||||
|
echo
|
||||||
|
exit 1
|
||||||
|
} >&2
|
||||||
|
|
||||||
|
# OS specific support (must be 'true' or 'false').
|
||||||
|
cygwin=false
|
||||||
|
msys=false
|
||||||
|
darwin=false
|
||||||
|
nonstop=false
|
||||||
|
case "$( uname )" in #(
|
||||||
|
CYGWIN* ) cygwin=true ;; #(
|
||||||
|
Darwin* ) darwin=true ;; #(
|
||||||
|
MSYS* | MINGW* ) msys=true ;; #(
|
||||||
|
NONSTOP* ) nonstop=true ;;
|
||||||
|
esac
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
# Determine the Java command to use to start the JVM.
|
||||||
|
if [ -n "$JAVA_HOME" ] ; then
|
||||||
|
if [ -x "$JAVA_HOME/jre/sh/java" ] ; then
|
||||||
|
# IBM's JDK on AIX uses strange locations for the executables
|
||||||
|
JAVACMD=$JAVA_HOME/jre/sh/java
|
||||||
|
else
|
||||||
|
JAVACMD=$JAVA_HOME/bin/java
|
||||||
|
fi
|
||||||
|
if [ ! -x "$JAVACMD" ] ; then
|
||||||
|
die "ERROR: JAVA_HOME is set to an invalid directory: $JAVA_HOME
|
||||||
|
|
||||||
|
Please set the JAVA_HOME variable in your environment to match the
|
||||||
|
location of your Java installation."
|
||||||
|
fi
|
||||||
|
else
|
||||||
|
JAVACMD=java
|
||||||
|
if ! command -v java >/dev/null 2>&1
|
||||||
|
then
|
||||||
|
die "ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH.
|
||||||
|
|
||||||
|
Please set the JAVA_HOME variable in your environment to match the
|
||||||
|
location of your Java installation."
|
||||||
|
fi
|
||||||
|
fi
|
||||||
|
|
||||||
|
# Increase the maximum file descriptors if we can.
|
||||||
|
if ! "$cygwin" && ! "$darwin" && ! "$nonstop" ; then
|
||||||
|
case $MAX_FD in #(
|
||||||
|
max*)
|
||||||
|
# In POSIX sh, ulimit -H is undefined. That's why the result is checked to see if it worked.
|
||||||
|
# shellcheck disable=SC2039,SC3045
|
||||||
|
MAX_FD=$( ulimit -H -n ) ||
|
||||||
|
warn "Could not query maximum file descriptor limit"
|
||||||
|
esac
|
||||||
|
case $MAX_FD in #(
|
||||||
|
'' | soft) :;; #(
|
||||||
|
*)
|
||||||
|
# In POSIX sh, ulimit -n is undefined. That's why the result is checked to see if it worked.
|
||||||
|
# shellcheck disable=SC2039,SC3045
|
||||||
|
ulimit -n "$MAX_FD" ||
|
||||||
|
warn "Could not set maximum file descriptor limit to $MAX_FD"
|
||||||
|
esac
|
||||||
|
fi
|
||||||
|
|
||||||
|
# Collect all arguments for the java command, stacking in reverse order:
|
||||||
|
# * args from the command line
|
||||||
|
# * the main class name
|
||||||
|
# * -classpath
|
||||||
|
# * -D...appname settings
|
||||||
|
# * --module-path (only if needed)
|
||||||
|
# * DEFAULT_JVM_OPTS, JAVA_OPTS, and GRADLE_OPTS environment variables.
|
||||||
|
|
||||||
|
# For Cygwin or MSYS, switch paths to Windows format before running java
|
||||||
|
if "$cygwin" || "$msys" ; then
|
||||||
|
APP_HOME=$( cygpath --path --mixed "$APP_HOME" )
|
||||||
|
|
||||||
|
JAVACMD=$( cygpath --unix "$JAVACMD" )
|
||||||
|
|
||||||
|
# Now convert the arguments - kludge to limit ourselves to /bin/sh
|
||||||
|
for arg do
|
||||||
|
if
|
||||||
|
case $arg in #(
|
||||||
|
-*) false ;; # don't mess with options #(
|
||||||
|
/?*) t=${arg#/} t=/${t%%/*} # looks like a POSIX filepath
|
||||||
|
[ -e "$t" ] ;; #(
|
||||||
|
*) false ;;
|
||||||
|
esac
|
||||||
|
then
|
||||||
|
arg=$( cygpath --path --ignore --mixed "$arg" )
|
||||||
|
fi
|
||||||
|
# Roll the args list around exactly as many times as the number of
|
||||||
|
# args, so each arg winds up back in the position where it started, but
|
||||||
|
# possibly modified.
|
||||||
|
#
|
||||||
|
# NB: a `for` loop captures its iteration list before it begins, so
|
||||||
|
# changing the positional parameters here affects neither the number of
|
||||||
|
# iterations, nor the values presented in `arg`.
|
||||||
|
shift # remove old arg
|
||||||
|
set -- "$@" "$arg" # push replacement arg
|
||||||
|
done
|
||||||
|
fi
|
||||||
|
|
||||||
|
|
||||||
|
# Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script.
|
||||||
|
DEFAULT_JVM_OPTS='"-Xmx64m" "-Xms64m"'
|
||||||
|
|
||||||
|
# Collect all arguments for the java command:
|
||||||
|
# * DEFAULT_JVM_OPTS, JAVA_OPTS, and optsEnvironmentVar are not allowed to contain shell fragments,
|
||||||
|
# and any embedded shellness will be escaped.
|
||||||
|
# * For example: A user cannot expect ${Hostname} to be expanded, as it is an environment variable and will be
|
||||||
|
# treated as '${Hostname}' itself on the command line.
|
||||||
|
|
||||||
|
set -- \
|
||||||
|
"-Dorg.gradle.appname=$APP_BASE_NAME" \
|
||||||
|
-jar "$APP_HOME/gradle/wrapper/gradle-wrapper.jar" \
|
||||||
|
"$@"
|
||||||
|
|
||||||
|
# Stop when "xargs" is not available.
|
||||||
|
if ! command -v xargs >/dev/null 2>&1
|
||||||
|
then
|
||||||
|
die "xargs is not available"
|
||||||
|
fi
|
||||||
|
|
||||||
|
# Use "xargs" to parse quoted args.
|
||||||
|
#
|
||||||
|
# With -n1 it outputs one arg per line, with the quotes and backslashes removed.
|
||||||
|
#
|
||||||
|
# In Bash we could simply go:
|
||||||
|
#
|
||||||
|
# readarray ARGS < <( xargs -n1 <<<"$var" ) &&
|
||||||
|
# set -- "${ARGS[@]}" "$@"
|
||||||
|
#
|
||||||
|
# but POSIX shell has neither arrays nor command substitution, so instead we
|
||||||
|
# post-process each arg (as a line of input to sed) to backslash-escape any
|
||||||
|
# character that might be a shell metacharacter, then use eval to reverse
|
||||||
|
# that process (while maintaining the separation between arguments), and wrap
|
||||||
|
# the whole thing up as a single "set" statement.
|
||||||
|
#
|
||||||
|
# This will of course break if any of these variables contains a newline or
|
||||||
|
# an unmatched quote.
|
||||||
|
#
|
||||||
|
|
||||||
|
eval "set -- $(
|
||||||
|
printf '%s\n' "$DEFAULT_JVM_OPTS $JAVA_OPTS $GRADLE_OPTS" |
|
||||||
|
xargs -n1 |
|
||||||
|
sed ' s~[^-[:alnum:]+,./:=@_]~\\&~g; ' |
|
||||||
|
tr '\n' ' '
|
||||||
|
)" '"$@"'
|
||||||
|
|
||||||
|
exec "$JAVACMD" "$@"
|
||||||
Vendored
+82
@@ -0,0 +1,82 @@
|
|||||||
|
@rem
|
||||||
|
@rem Copyright 2015 the original author or authors.
|
||||||
|
@rem
|
||||||
|
@rem Licensed under the Apache License, Version 2.0 (the "License");
|
||||||
|
@rem you may not use this file except in compliance with the License.
|
||||||
|
@rem You may obtain a copy of the License at
|
||||||
|
@rem
|
||||||
|
@rem https://www.apache.org/licenses/LICENSE-2.0
|
||||||
|
@rem
|
||||||
|
@rem Unless required by applicable law or agreed to in writing, software
|
||||||
|
@rem distributed under the License is distributed on an "AS IS" BASIS,
|
||||||
|
@rem WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||||
|
@rem See the License for the specific language governing permissions and
|
||||||
|
@rem limitations under the License.
|
||||||
|
@rem
|
||||||
|
@rem SPDX-License-Identifier: Apache-2.0
|
||||||
|
@rem
|
||||||
|
|
||||||
|
@if "%DEBUG%"=="" @echo off
|
||||||
|
@rem ##########################################################################
|
||||||
|
@rem
|
||||||
|
@rem gradlew startup script for Windows
|
||||||
|
@rem
|
||||||
|
@rem ##########################################################################
|
||||||
|
|
||||||
|
@rem Set local scope for the variables, and ensure extensions are enabled
|
||||||
|
setlocal EnableExtensions
|
||||||
|
|
||||||
|
set DIRNAME=%~dp0
|
||||||
|
if "%DIRNAME%"=="" set DIRNAME=.
|
||||||
|
@rem This is normally unused
|
||||||
|
set APP_BASE_NAME=%~n0
|
||||||
|
set APP_HOME=%DIRNAME%
|
||||||
|
|
||||||
|
@rem Resolve any "." and ".." in APP_HOME to make it shorter.
|
||||||
|
for %%i in ("%APP_HOME%") do set APP_HOME=%%~fi
|
||||||
|
|
||||||
|
@rem Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script.
|
||||||
|
set DEFAULT_JVM_OPTS="-Xmx64m" "-Xms64m"
|
||||||
|
|
||||||
|
@rem Find java.exe
|
||||||
|
if defined JAVA_HOME goto findJavaFromJavaHome
|
||||||
|
|
||||||
|
set JAVA_EXE=java.exe
|
||||||
|
%JAVA_EXE% -version >NUL 2>&1
|
||||||
|
if %ERRORLEVEL% equ 0 goto execute
|
||||||
|
|
||||||
|
echo. 1>&2
|
||||||
|
echo ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH. 1>&2
|
||||||
|
echo. 1>&2
|
||||||
|
echo Please set the JAVA_HOME variable in your environment to match the 1>&2
|
||||||
|
echo location of your Java installation. 1>&2
|
||||||
|
|
||||||
|
"%COMSPEC%" /c exit 1
|
||||||
|
|
||||||
|
:findJavaFromJavaHome
|
||||||
|
set JAVA_HOME=%JAVA_HOME:"=%
|
||||||
|
set JAVA_EXE=%JAVA_HOME%/bin/java.exe
|
||||||
|
|
||||||
|
if exist "%JAVA_EXE%" goto execute
|
||||||
|
|
||||||
|
echo. 1>&2
|
||||||
|
echo ERROR: JAVA_HOME is set to an invalid directory: %JAVA_HOME% 1>&2
|
||||||
|
echo. 1>&2
|
||||||
|
echo Please set the JAVA_HOME variable in your environment to match the 1>&2
|
||||||
|
echo location of your Java installation. 1>&2
|
||||||
|
|
||||||
|
"%COMSPEC%" /c exit 1
|
||||||
|
|
||||||
|
:execute
|
||||||
|
@rem Setup the command line
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
@rem Execute gradlew
|
||||||
|
@rem endlocal doesn't take effect until after the line is parsed and variables are expanded
|
||||||
|
@rem which allows us to clear the local environment before executing the java command
|
||||||
|
endlocal & "%JAVA_EXE%" %DEFAULT_JVM_OPTS% %JAVA_OPTS% %GRADLE_OPTS% "-Dorg.gradle.appname=%APP_BASE_NAME%" -jar "%APP_HOME%\gradle\wrapper\gradle-wrapper.jar" %* & call :exitWithErrorLevel
|
||||||
|
|
||||||
|
:exitWithErrorLevel
|
||||||
|
@rem Use "%COMSPEC%" /c exit to allow operators to work properly in scripts
|
||||||
|
"%COMSPEC%" /c exit %ERRORLEVEL%
|
||||||
@@ -0,0 +1,4 @@
|
|||||||
|
pluginManagement { repositories { google(); mavenCentral(); gradlePluginPortal() } }
|
||||||
|
dependencyResolutionManagement { repositoriesMode.set(RepositoriesMode.FAIL_ON_PROJECT_REPOS); repositories { google(); mavenCentral() } }
|
||||||
|
rootProject.name = "LiteLLM Dashboard"
|
||||||
|
include(":app")
|
||||||
@@ -0,0 +1,52 @@
|
|||||||
|
"""Local development fixture. Run: python tools/mock_proxy.py; adb reverse tcp:8765 tcp:8765."""
|
||||||
|
from http.server import BaseHTTPRequestHandler, HTTPServer
|
||||||
|
from urllib.parse import urlparse, parse_qs
|
||||||
|
import json
|
||||||
|
|
||||||
|
|
||||||
|
class Handler(BaseHTTPRequestHandler):
|
||||||
|
def do_POST(self):
|
||||||
|
if self.headers.get("Authorization") != "Bearer sk-demo":
|
||||||
|
return self.reply(401, {"error": {"message": "Invalid API key"}})
|
||||||
|
body = json.loads(self.rfile.read(int(self.headers.get("Content-Length", "0"))))
|
||||||
|
path = urlparse(self.path).path
|
||||||
|
if path == "/key/generate":
|
||||||
|
return self.reply(200, {"key": "sk-new-demo-key", "key_alias": body.get("key_alias")})
|
||||||
|
if path == "/team/new":
|
||||||
|
return self.reply(200, {"team_id": "new-team", "team_alias": body.get("team_alias")})
|
||||||
|
if path == "/model/new":
|
||||||
|
return self.reply(200, {"model_name": body.get("model_name")})
|
||||||
|
self.reply(404, {"error": {"message": "Not found"}})
|
||||||
|
|
||||||
|
def do_GET(self):
|
||||||
|
if self.headers.get("Authorization") != "Bearer sk-demo":
|
||||||
|
return self.reply(401, {"error": {"message": "Invalid API key"}})
|
||||||
|
url = urlparse(self.path)
|
||||||
|
page = int(parse_qs(url.query).get("page", ["1"])[0])
|
||||||
|
routes = {
|
||||||
|
"/model/info": {"data": [
|
||||||
|
{"model_name": "gpt-4o", "litellm_params": {"model": "openai/gpt-4o"}, "model_info": {"id": "model-1", "litellm_provider": "openai", "mode": "chat", "max_tokens": 128000}},
|
||||||
|
{"model_name": "claude-sonnet", "litellm_params": {"model": "anthropic/claude-sonnet"}, "model_info": {"id": "model-2", "litellm_provider": "anthropic", "mode": "chat"}},
|
||||||
|
]},
|
||||||
|
"/key/list": {"keys": [{"key_alias": "Production", "token": "hashed-token", "user_id": "alvin", "team_id": "core", "spend": 42.12, "max_budget": 100, "blocked": False}]},
|
||||||
|
"/team/list": [{"team_alias": "Core", "team_id": "core", "spend": 98.45, "max_budget": 250, "members": ["alvin", "sam"]}],
|
||||||
|
"/global/spend": {"spend": 234.56},
|
||||||
|
"/global/activity": {"total_requests": 1234, "successful_requests": 1221},
|
||||||
|
"/global/spend/report": [{"group_by_day": "2026-11-17T00:00:00+00:00", "total_spend": 4.5}, {"group_by_day": "2026-11-18T00:00:00+00:00", "total_spend": 7.9}],
|
||||||
|
"/spend/logs/v2": {"data": [{"request_id": f"req-{page}", "model": "gpt-4o", "startTime": "2026-11-19T08:00:00", "status": "success", "spend": 0.024, "total_tokens": 945, "team_id": "core"}], "total": 31, "page": page, "page_size": 30},
|
||||||
|
}
|
||||||
|
if url.path not in routes:
|
||||||
|
return self.reply(404, {"error": {"message": "Not found"}})
|
||||||
|
self.reply(200, routes[url.path])
|
||||||
|
|
||||||
|
def reply(self, status, value):
|
||||||
|
payload = json.dumps(value).encode()
|
||||||
|
self.send_response(status)
|
||||||
|
self.send_header("Content-Type", "application/json")
|
||||||
|
self.send_header("Content-Length", str(len(payload)))
|
||||||
|
self.end_headers()
|
||||||
|
self.wfile.write(payload)
|
||||||
|
|
||||||
|
|
||||||
|
if __name__ == "__main__":
|
||||||
|
HTTPServer(("0.0.0.0", 8765), Handler).serve_forever()
|
||||||
Reference in new issue
Block a user