Skip to content

armgit / uzu

Public Imported from GitHub
0

A high-performance inference engine for AI models

Bindings migration 2/n (#354)

Aleksei Savinb0441c7e75cf
diff --git a/.env.sample b/.env.sample
index 9f46e2b71..42ed54a35 100644
--- a/.env.sample
+++ b/.env.sample
@@ -1,3 +1,6 @@
MIRAI_API_KEY=
HF_TOKEN=
-OPENAI_API_KEY=
\ No newline at end of file
+OPENAI_API_KEY=
+BASETEN_API_KEY=
+ANTHROPIC_API_KEY=
+OPENROUTER_API_KEY=
\ No newline at end of file
diff --git a/Cargo.lock b/Cargo.lock
index be08b8465..d45c984f8 100644
--- a/Cargo.lock
+++ b/Cargo.lock
@@ -388,7 +388,7 @@ dependencies = [
"cc",
"cxx-gen",
"indexmap 1.9.3",
- "indoc",
+ "indoc 1.0.9",
"itertools 0.10.5",
"log",
"miette",
@@ -547,6 +547,7 @@ dependencies = [
"serde",
"serde_json",
"serde_json5",
+ "shoji",
"syn 2.0.117",
"sysinfo",
"tempfile",
@@ -680,6 +681,12 @@ version = "0.7.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "aad18937a628ec6abcd26d1489012cc0e18c21798210f491af69ded9b881106d"
+[[package]]
+name = "bitflags"
+version = "1.3.2"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "bef38d45163c2f1dde094a7dfd33ccf595c92905c8f8f4fdc18d06fb1037718a"
+
[[package]]
name = "bitflags"
version = "2.11.1"
@@ -1049,6 +1056,22 @@ dependencies = [
"uzu",
]
+[[package]]
+name = "cli-storage"
+version = "0.1.9"
+dependencies = [
+ "crossterm",
+ "dotenvy",
+ "futures-util",
+ "ratatui",
+ "shoji",
+ "tokio",
+ "tracing",
+ "tracing-appender",
+ "tracing-subscriber",
+ "uzu",
+]
+
[[package]]
name = "cmake"
version = "0.1.58"
@@ -1066,7 +1089,7 @@ checksum = "af491d569909a7e4dee0ad7db7f5341fef5c614d5b8ec8cf765732aba3cff681"
dependencies = [
"serde",
"termcolor",
- "unicode-width 0.2.2",
+ "unicode-width 0.2.0",
]
[[package]]
@@ -1098,7 +1121,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "958c5d6ecf1f214b4c2bbbbf6ab9523a864bd136dcf71a7e8904799acfe1ad47"
dependencies = [
"unicode-segmentation",
- "unicode-width 0.2.2",
+ "unicode-width 0.2.0",
]
[[package]]
@@ -1124,7 +1147,7 @@ checksum = "d64e8af5551369d19cf50138de61f1c42074ab970f74e99be916646777f8fc87"
dependencies = [
"encode_unicode",
"libc",
- "unicode-width 0.2.2",
+ "unicode-width 0.2.0",
"windows-sys 0.61.2",
]
@@ -1394,6 +1417,16 @@ dependencies = [
"typenum",
]
+[[package]]
+name = "csscolorparser"
+version = "0.6.2"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "eb2a7d3066da2de787b7f032c736763eb7ae5d355f81a68bab2675a96008b0bf"
+dependencies = [
+ "lab",
+ "phf",
+]
+
[[package]]
name = "ctor"
version = "0.10.0"
@@ -1615,6 +1648,12 @@ version = "2.10.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "d7a1e2f27636f116493b8b860f5546edb47c8d8f8ea73e1d2a20be88e28d1fea"
+[[package]]
+name = "deltae"
+version = "0.3.2"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "5729f5117e208430e437df2f4843f5e5952997175992d1414f94c57d61e270b4"
+
[[package]]
name = "depfile"
version = "0.1.1"
@@ -1978,6 +2017,15 @@ dependencies = [
"cc",
]
+[[package]]
+name = "euclid"
+version = "0.22.14"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "f1a05365e3b1c6d1650318537c7460c6923f1abdd272ad6842baa2b509957a06"
+dependencies = [
+ "num-traits",
+]
+
[[package]]
name = "exr"
version = "1.74.0"
@@ -1993,6 +2041,16 @@ dependencies = [
"zune-inflate",
]
+[[package]]
+name = "fancy-regex"
+version = "0.11.0"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "b95f7c0680e4142284cf8b22c14a476e87d61b004a3a0861872b32ef7ead40a2"
+dependencies = [
+ "bit-set 0.5.3",
+ "regex",
+]
+
[[package]]
name = "fancy-regex"
version = "0.13.0"
@@ -2075,6 +2133,17 @@ dependencies = [
"version_check",
]
+[[package]]
+name = "filedescriptor"
+version = "0.8.3"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "e40758ed24c9b2eeb76c35fb0aebc66c626084edd827e07e1552279814c6682d"
+dependencies = [
+ "libc",
+ "thiserror 1.0.69",
+ "winapi",
+]
+
[[package]]
name = "filetime"
version = "0.2.27"
@@ -2092,6 +2161,18 @@ version = "0.1.9"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "5baebc0774151f905a1a2cc41989300b1e6fbb29aff0ceffa1064fdd3088d582"
+[[package]]
+name = "finl_unicode"
+version = "1.4.0"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "9844ddc3a6e533d62bba727eb6c28b5d360921d5175e9ff0f1e621a5c590a4d5"
+
+[[package]]
+name = "fixedbitset"
+version = "0.4.2"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "0ce7134b9999ecaf8bcd65542e436736ef32ddca1b3e06094cb6ec5755203b80"
+
[[package]]
name = "flate2"
version = "1.1.9"
@@ -2445,29 +2526,20 @@ dependencies = [
name = "hanashi"
version = "0.1.9"
dependencies = [
- "bindings",
"fancy-regex 0.17.0",
"indexmap 2.14.0",
"libc",
"llm_json",
"minijinja",
"minijinja-contrib",
- "napi",
- "napi-build",
- "napi-derive",
"openai-harmony",
- "pyo3",
"regex",
"serde",
- "serde-wasm-bindgen",
"serde_json",
+ "shoji",
"thiserror 2.0.18",
"token-stream-parser",
"tokenizers",
- "tsify",
- "uniffi",
- "wasm-bindgen",
- "wasm-bindgen-futures",
]
[[package]]
@@ -2948,7 +3020,7 @@ checksum = "25470f23803092da7d239834776d653104d551bc4d7eacaf31e6837854b8e9eb"
dependencies = [
"console",
"portable-atomic",
- "unicode-width 0.2.2",
+ "unicode-width 0.2.0",
"unit-prefix",
"web-time",
]
@@ -2959,6 +3031,15 @@ version = "1.0.9"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "bfa799dd5ed20a7e349f3b4639aa80d74549c81716d9ec4f994c9b5815598306"
+[[package]]
+name = "indoc"
+version = "2.0.7"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "79cf5c93f93228cf8efb3ba362535fb11199ac548a09ce117c9b1adc3030d706"
+dependencies = [
+ "rustversion",
+]
+
[[package]]
name = "inlinable_string"
version = "0.1.15"
@@ -2976,7 +3057,20 @@ dependencies = [
"dyn-clone",
"fuzzy-matcher",
"unicode-segmentation",
- "unicode-width 0.2.2",
+ "unicode-width 0.2.0",
+]
+
+[[package]]
+name = "instability"
+version = "0.3.12"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "5eb2d60ef19920a3a9193c3e371f726ec1dafc045dac788d0fb3704272458971"
+dependencies = [
+ "darling 0.23.0",
+ "indoc 2.0.7",
+ "proc-macro2",
+ "quote",
+ "syn 2.0.117",
]
[[package]]
@@ -3185,6 +3279,23 @@ dependencies = [
"uuid-simd",
]
+[[package]]
+name = "kasuari"
+version = "0.4.12"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "bde5057d6143cc94e861d90f591b9303d6716c6b9602309150bd068853c10899"
+dependencies = [
+ "hashbrown 0.16.1",
+ "portable-atomic",
+ "thiserror 2.0.18",
+]
+
+[[package]]
+name = "lab"
+version = "0.11.0"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "bf36173d4167ed999940f804952e6b08197cae5ad5d572eb4db150ce8ad5d58f"
+
[[package]]
name = "lazy_static"
version = "1.5.0"
@@ -3257,6 +3368,15 @@ dependencies = [
"redox_syscall 0.7.4",
]
+[[package]]
+name = "line-clipping"
+version = "0.3.7"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "3f50e8f47623268b5407192d26876c4d7f89d686ca130fdc53bced4814cd29f8"
+dependencies = [
+ "bitflags 2.11.1",
+]
+
[[package]]
name = "link-cplusplus"
version = "1.0.12"
@@ -3368,12 +3488,31 @@ dependencies = [
"imgref",
]
+[[package]]
+name = "lru"
+version = "0.16.4"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "7f66e8d5d03f609abc3a39e6f08e4164ebf1447a732906d39eb9b99b7919ef39"
+dependencies = [
+ "hashbrown 0.16.1",
+]
+
[[package]]
name = "lru-slab"
version = "0.1.2"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "112b39cec0b298b6c1999fee3e31427f74f676e4cb9879ed1a121b43661a4154"
+[[package]]
+name = "mac_address"
+version = "1.1.8"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "c0aeb26bf5e836cc1c341c8106051b573f1766dfa05aa87f0b98be5e51b02303"
+dependencies = [
+ "nix 0.29.0",
+ "winapi",
+]
+
[[package]]
name = "mach2"
version = "0.6.0"
@@ -3450,12 +3589,27 @@ dependencies = [
"libc",
]
+[[package]]
+name = "memmem"
+version = "0.1.1"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "a64a92489e2744ce060c349162be1c5f33c6969234104dbd99ddb5feb08b8c15"
+
[[package]]
name = "memo-map"
version = "0.3.3"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "38d1115007560874e373613744c6fba374c17688327a71c1476d1a5954cc857b"
+[[package]]
+name = "memoffset"
+version = "0.9.1"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "488016bfae457b036d996092f6cb448677611ce4449e970ceaf42695203f218a"
+dependencies = [
+ "autocfg",
+]
+
[[package]]
name = "micromap"
version = "0.3.0"
@@ -3630,28 +3784,13 @@ dependencies = [
name = "nagare"
version = "0.1.9"
dependencies = [
- "chrono",
- "dirs",
- "download-manager",
- "futures",
- "futures-util",
+ "hanashi",
"indexmap 2.14.0",
- "indicatif",
- "objc2",
- "objc2-foundation",
- "objc2-security",
"reqwest 0.13.2",
"serde",
"serde_json",
- "sysinfo",
- "tempfile",
+ "shoji",
"thiserror 2.0.18",
- "tokio",
- "tokio-stream",
- "tracing",
- "tracing-appender",
- "tracing-subscriber",
- "uuid",
]
[[package]]
@@ -3762,6 +3901,19 @@ dependencies = [
"void",
]
+[[package]]
+name = "nix"
+version = "0.29.0"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "71e2746dc3a24dd78b3cfcb7be93368c6de9963d30f43a6a73998a9cf4b17b46"
+dependencies = [
+ "bitflags 2.11.1",
+ "cfg-if 1.0.4",
+ "cfg_aliases",
+ "libc",
+ "memoffset",
+]
+
[[package]]
name = "nix"
version = "0.31.2"
@@ -3939,6 +4091,15 @@ dependencies = [
"libc",
]
+[[package]]
+name = "num_threads"
+version = "0.1.7"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "5c7398b9c8b70908f6371f47ed36737907c87c52af34c268fed0bf0ceb92ead9"
+dependencies = [
+ "libc",
+]
+
[[package]]
name = "numtoa"
version = "0.3.1"
@@ -4071,6 +4232,22 @@ version = "11.1.5"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "d6790f58c7ff633d8771f42965289203411a5e5c68388703c06e14f24770b41e"
+[[package]]
+name = "openai-api-rs"
+version = "10.0.1"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "ba538da8c96b5f486ec8706a1b4663fa9c46be33cf12f8bf43e82e4c7da8acb5"
+dependencies = [
+ "bytes",
+ "futures-util",
+ "reqwest 0.12.28",
+ "serde",
+ "serde_json",
+ "tokio",
+ "tokio-tungstenite",
+ "url",
+]
+
[[package]]
name = "openai-harmony"
version = "0.0.8"
@@ -4145,6 +4322,15 @@ version = "0.2.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "04744f49eae99ab78e0d5c0b603ab218f515ea8cfe5a456d7629ad883a3b6e7d"
+[[package]]
+name = "ordered-float"
+version = "4.6.0"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "7bb71e1b3fa6ca1c61f383464aaf2bb0e2f8e772a1f01d486832464de363b951"
+dependencies = [
+ "num-traits",
+]
+
[[package]]
name = "outref"
version = "0.5.2"
@@ -4277,6 +4463,58 @@ dependencies = [
"sha2",
]
+[[package]]
+name = "phf"
+version = "0.11.3"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "1fd6780a80ae0c52cc120a26a1a42c1ae51b247a253e4e06113d23d2c2edd078"
+dependencies = [
+ "phf_macros",
+ "phf_shared",
+]
+
+[[package]]
+name = "phf_codegen"
+version = "0.11.3"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "aef8048c789fa5e851558d709946d6d79a8ff88c0440c587967f8e94bfb1216a"
+dependencies = [
+ "phf_generator",
+ "phf_shared",
+]
+
+[[package]]
+name = "phf_generator"
+version = "0.11.3"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "3c80231409c20246a13fddb31776fb942c38553c51e871f8cbd687a4cfb5843d"
+dependencies = [
+ "phf_shared",
+ "rand 0.8.5",
+]
+
+[[package]]
+name = "phf_macros"
+version = "0.11.3"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "f84ac04429c13a7ff43785d75ad27569f2951ce0ffd30a3321230db2fc727216"
+dependencies = [
+ "phf_generator",
+ "phf_shared",
+ "proc-macro2",
+ "quote",
+ "syn 2.0.117",
+]
+
+[[package]]
+name = "phf_shared"
+version = "0.11.3"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "67eabc2ef2a60eb7faa00097bd1ffdb5bd28e62bf39990626a582201b7a754e5"
+dependencies = [
+ "siphasher",
+]
+
[[package]]
name = "pin-project-lite"
version = "0.2.17"
@@ -4757,6 +4995,91 @@ version = "1.7.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "973443cf09a9c8656b574a866ab68dfa19f0867d0340648c7d2f6a71b8a8ea68"
+[[package]]
+name = "ratatui"
+version = "0.30.0"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "d1ce67fb8ba4446454d1c8dbaeda0557ff5e94d39d5e5ed7f10a65eb4c8266bc"
+dependencies = [
+ "instability",
+ "ratatui-core",
+ "ratatui-crossterm",
+ "ratatui-macros",
+ "ratatui-termwiz",
+ "ratatui-widgets",
+]
+
+[[package]]
+name = "ratatui-core"
+version = "0.1.0"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "5ef8dea09a92caaf73bff7adb70b76162e5937524058a7e5bff37869cbbec293"
+dependencies = [
+ "bitflags 2.11.1",
+ "compact_str",
+ "hashbrown 0.16.1",
+ "indoc 2.0.7",
+ "itertools 0.14.0",
+ "kasuari",
+ "lru",
+ "strum",
+ "thiserror 2.0.18",
+ "unicode-segmentation",
+ "unicode-truncate",
+ "unicode-width 0.2.0",
+]
+
+[[package]]
+name = "ratatui-crossterm"
+version = "0.1.0"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "577c9b9f652b4c121fb25c6a391dd06406d3b092ba68827e6d2f09550edc54b3"
+dependencies = [
+ "cfg-if 1.0.4",
+ "crossterm",
+ "instability",
+ "ratatui-core",
+]
+
+[[package]]
+name = "ratatui-macros"
+version = "0.7.0"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "a7f1342a13e83e4bb9d0b793d0ea762be633f9582048c892ae9041ef39c936f4"
+dependencies = [
+ "ratatui-core",
+ "ratatui-widgets",
+]
+
+[[package]]
+name = "ratatui-termwiz"
+version = "0.1.0"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "0f76fe0bd0ed4295f0321b1676732e2454024c15a35d01904ddb315afd3d545c"
+dependencies = [
+ "ratatui-core",
+ "termwiz",
+]
+
+[[package]]
+name = "ratatui-widgets"
+version = "0.3.0"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "d7dbfa023cd4e604c2553483820c5fe8aa9d71a42eea5aa77c6e7f35756612db"
+dependencies = [
+ "bitflags 2.11.1",
+ "hashbrown 0.16.1",
+ "indoc 2.0.7",
+ "instability",
+ "itertools 0.14.0",
+ "line-clipping",
+ "ratatui-core",
+ "strum",
+ "time",
+ "unicode-segmentation",
+ "unicode-width 0.2.0",
+]
+
[[package]]
name = "rav1e"
version = "0.8.1"
@@ -5645,6 +5968,26 @@ version = "1.3.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "0fda2ff0d084019ba4d7c6f371c95d8fd75ce3524c3cb8fb653a3023f6323e64"
+[[package]]
+name = "shoji"
+version = "0.1.9"
+dependencies = [
+ "bindings",
+ "indexmap 2.14.0",
+ "napi",
+ "napi-build",
+ "napi-derive",
+ "pyo3",
+ "serde",
+ "serde-wasm-bindgen",
+ "serde_json",
+ "thiserror 2.0.18",
+ "tsify",
+ "uniffi",
+ "wasm-bindgen",
+ "wasm-bindgen-futures",
+]
+
[[package]]
name = "signal-hook"
version = "0.3.18"
@@ -5811,6 +6154,27 @@ version = "0.11.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "7da8b5736845d9f2fcb837ea5d9e2628564b3b043a70948a3f0b778838c5fb4f"
+[[package]]
+name = "strum"
+version = "0.27.2"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "af23d6f6c1a224baef9d3f61e287d2761385a5b88fdab4eb4c6f11aeb54c4bcf"
+dependencies = [
+ "strum_macros",
+]
+
+[[package]]
+name = "strum_macros"
+version = "0.27.2"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "7695ce3845ea4b33927c055a39dc438a45b059f7c1b3d91d38d10355fb8cbca7"
+dependencies = [
+ "heck",
+ "proc-macro2",
+ "quote",
+ "syn 2.0.117",
+]
+
[[package]]
name = "subtle"
version = "2.6.1"
@@ -5922,6 +6286,69 @@ dependencies = [
"winapi-util",
]
+[[package]]
+name = "terminfo"
+version = "0.9.0"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "d4ea810f0692f9f51b382fff5893887bb4580f5fa246fde546e0b13e7fcee662"
+dependencies = [
+ "fnv",
+ "nom 7.1.3",
+ "phf",
+ "phf_codegen",
+]
+
+[[package]]
+name = "termios"
+version = "0.3.3"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "411c5bf740737c7918b8b1fe232dca4dc9f8e754b8ad5e20966814001ed0ac6b"
+dependencies = [
+ "libc",
+]
+
+[[package]]
+name = "termwiz"
+version = "0.23.3"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "4676b37242ccbd1aabf56edb093a4827dc49086c0ffd764a5705899e0f35f8f7"
+dependencies = [
+ "anyhow",
+ "base64 0.22.1",
+ "bitflags 2.11.1",
+ "fancy-regex 0.11.0",
+ "filedescriptor",
+ "finl_unicode",
+ "fixedbitset",
+ "hex",
+ "lazy_static",
+ "libc",
+ "log",
+ "memmem",
+ "nix 0.29.0",
+ "num-derive",
+ "num-traits",
+ "ordered-float",
+ "pest",
+ "pest_derive",
+ "phf",
+ "sha2",
+ "signal-hook",
+ "siphasher",
+ "terminfo",
+ "termios",
+ "thiserror 1.0.69",
+ "ucd-trie",
+ "unicode-segmentation",
+ "vtparse",
+ "wezterm-bidi",
+ "wezterm-blob-leases",
+ "wezterm-color-types",
+ "wezterm-dynamic",
+ "wezterm-input-types",
+ "winapi",
+]
+
[[package]]
name = "test-tag"
version = "0.1.6"
@@ -6019,7 +6446,9 @@ checksum = "743bd48c283afc0388f9b8827b976905fb217ad9e647fae3a379a9283c4def2c"
dependencies = [
"deranged",
"itoa",
+ "libc",
"num-conv",
+ "num_threads",
"powerfmt",
"serde_core",
"time-core",
@@ -6197,6 +6626,20 @@ dependencies = [
"tokio-util",
]
+[[package]]
+name = "tokio-tungstenite"
+version = "0.28.0"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "d25a406cddcc431a75d3d9afc6a7c0f7428d4891dd973e4d54c56b46127bf857"
+dependencies = [
+ "futures-util",
+ "log",
+ "native-tls",
+ "tokio",
+ "tokio-native-tls",
+ "tungstenite",
+]
+
[[package]]
name = "tokio-util"
version = "0.7.18"
@@ -6462,6 +6905,24 @@ dependencies = [
"syn 2.0.117",
]
+[[package]]
+name = "tungstenite"
+version = "0.28.0"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "8628dcc84e5a09eb3d8423d6cb682965dea9133204e8fb3efee74c2a0c259442"
+dependencies = [
+ "bytes",
+ "data-encoding",
+ "http 1.4.0",
+ "httparse",
+ "log",
+ "native-tls",
+ "rand 0.9.4",
+ "sha1",
+ "thiserror 2.0.18",
+ "utf-8",
+]
+
[[package]]
name = "typenum"
version = "1.19.0"
@@ -6532,6 +6993,17 @@ version = "1.13.2"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "9629274872b2bfaf8d66f5f15725007f635594914870f65218920345aa11aa8c"
+[[package]]
+name = "unicode-truncate"
+version = "2.0.1"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "16b380a1238663e5f8a691f9039c73e1cdae598a30e9855f541d29b08b53e9a5"
+dependencies = [
+ "itertools 0.14.0",
+ "unicode-segmentation",
+ "unicode-width 0.2.0",
+]
+
[[package]]
name = "unicode-width"
version = "0.1.14"
@@ -6540,9 +7012,9 @@ checksum = "7dd6e30e90baa6f72411720665d41d89b9a3d039dc45b8faea1ddd07f617f6af"
[[package]]
name = "unicode-width"
-version = "0.2.2"
+version = "0.2.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "b4ac048d71ede7ee76d585517add45da530660ef4390e49b098733c6e897f254"
+checksum = "1fc81956842c57dac11422a97c3b8195a1ff727f06e85c84ed2e8aa277c9a0fd"
[[package]]
name = "unicode-xid"
@@ -6735,6 +7207,12 @@ dependencies = [
"serde",
]
+[[package]]
+name = "utf-8"
+version = "0.7.6"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "09cc8ee72d2a9becf2f2febe0205bbed8fc6615b7cb429ad062dc7b7ddd036a9"
+
[[package]]
name = "utf8-zero"
version = "0.8.1"
@@ -6759,6 +7237,7 @@ version = "1.23.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "5ac8b6f42ead25368cf5b098aeb3dc8a1a2c05a3eee8a9a1a68c640edbfc79d9"
dependencies = [
+ "atomic 0.6.1",
"getrandom 0.4.2",
"js-sys",
"sha1_smol",
@@ -6780,12 +7259,43 @@ name = "uzu"
version = "0.1.9"
dependencies = [
"backend-uzu",
+ "bindings",
+ "chrono",
+ "dirs",
"dotenvy",
+ "download-manager",
+ "futures",
+ "futures-util",
+ "indexmap 2.14.0",
+ "indicatif",
"nagare",
+ "napi",
+ "napi-build",
+ "napi-derive",
+ "objc2",
+ "objc2-foundation",
+ "objc2-security",
+ "openai-api-rs",
+ "pyo3",
+ "regex",
+ "reqwest 0.13.2",
"serde",
+ "serde-wasm-bindgen",
+ "serde_json",
+ "shoji",
+ "sysinfo",
+ "tempfile",
"thiserror 2.0.18",
"tokio",
"tokio-stream",
+ "tracing",
+ "tracing-appender",
+ "tracing-subscriber",
+ "tsify",
+ "uniffi",
+ "uuid",
+ "wasm-bindgen",
+ "wasm-bindgen-futures",
]
[[package]]
@@ -6829,6 +7339,15 @@ version = "0.8.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "5c3082ca00d5a5ef149bb8b555a72ae84c9c59f7250f013ac822ac2e49b19c64"
+[[package]]
+name = "vtparse"
+version = "0.6.2"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "6d9b2acfb050df409c972a37d3b8e08cdea3bddb0c09db9d53137e504cfabed0"
+dependencies = [
+ "utf8parse",
+]
+
[[package]]
name = "wait-timeout"
version = "0.2.1"
@@ -7051,6 +7570,78 @@ version = "0.1.12"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "a28ac98ddc8b9274cb41bb4d9d4d5c425b6020c50c46f25559911905610b4a88"
+[[package]]
+name = "wezterm-bidi"
+version = "0.2.3"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "0c0a6e355560527dd2d1cf7890652f4f09bb3433b6aadade4c9b5ed76de5f3ec"
+dependencies = [
+ "log",
+ "wezterm-dynamic",
+]
+
+[[package]]
+name = "wezterm-blob-leases"
+version = "0.1.1"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "692daff6d93d94e29e4114544ef6d5c942a7ed998b37abdc19b17136ea428eb7"
+dependencies = [
+ "getrandom 0.3.4",
+ "mac_address",
+ "sha2",
+ "thiserror 1.0.69",
+ "uuid",
+]
+
+[[package]]
+name = "wezterm-color-types"
+version = "0.3.0"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "7de81ef35c9010270d63772bebef2f2d6d1f2d20a983d27505ac850b8c4b4296"
+dependencies = [
+ "csscolorparser",
+ "deltae",
+ "lazy_static",
+ "wezterm-dynamic",
+]
+
+[[package]]
+name = "wezterm-dynamic"
+version = "0.2.1"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "5f2ab60e120fd6eaa68d9567f3226e876684639d22a4219b313ff69ec0ccd5ac"
+dependencies = [
+ "log",
+ "ordered-float",
+ "strsim",
+ "thiserror 1.0.69",
+ "wezterm-dynamic-derive",
+]
+
+[[package]]
+name = "wezterm-dynamic-derive"
+version = "0.1.1"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "46c0cf2d539c645b448eaffec9ec494b8b19bd5077d9e58cb1ae7efece8d575b"
+dependencies = [
+ "proc-macro2",
+ "quote",
+ "syn 1.0.109",
+]
+
+[[package]]
+name = "wezterm-input-types"
+version = "0.1.0"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "7012add459f951456ec9d6c7e6fc340b1ce15d6fc9629f8c42853412c029e57e"
+dependencies = [
+ "bitflags 1.3.2",
+ "euclid",
+ "lazy_static",
+ "serde",
+ "wezterm-dynamic",
+]
+
[[package]]
name = "winapi"
version = "0.3.9"
diff --git a/Cargo.toml b/Cargo.toml
index a1a578ed2..450193eef 100644
--- a/Cargo.toml
+++ b/Cargo.toml
@@ -2,6 +2,7 @@
members = [
"crates/dsl",
"crates/bindings",
+ "crates/shoji",
"crates/json-transform",
"crates/token-stream-parser",
"crates/hanashi",
@@ -11,6 +12,7 @@ members = [
"crates/uzu",
"crates/benchmarks",
"crates/cli",
+ "crates/cli-storage",
]
resolver = "3"
@@ -25,6 +27,7 @@ repository = "https://github.com/trymirai/uzu"
[workspace.dependencies]
dsl = { path = "crates/dsl" }
bindings = { path = "crates/bindings", default-features = false }
+shoji = { path = "crates/shoji", default-features = false }
json-transform = { path = "crates/json-transform", default-features = false }
token-stream-parser = { path = "crates/token-stream-parser", default-features = false }
hanashi = { path = "crates/hanashi", default-features = false }
@@ -134,6 +137,9 @@ tsify = { version = "0.5.6", features = ["js"] }
openai-harmony = "0.0.8"
dirs = "6.0.0"
dotenvy = "0.15.7"
+ratatui = "0.30.0"
+crossterm = "0.29.0"
+openai-api-rs = "10.0.0"
[profile.dev.build-override]
opt-level = 3
diff --git a/crates/backend-uzu/Cargo.toml b/crates/backend-uzu/Cargo.toml
index a008b2b2b..1874c0edc 100644
--- a/crates/backend-uzu/Cargo.toml
+++ b/crates/backend-uzu/Cargo.toml
@@ -10,6 +10,7 @@ build = "build/main.rs"
[dependencies]
dsl.workspace = true
+shoji.workspace = true
half.workspace = true
ndarray.workspace = true
serde.workspace = true
diff --git a/crates/backend-uzu/src/inference_backend.rs b/crates/backend-uzu/src/inference_backend.rs
new file mode 100644
index 000000000..ff12d9692
--- /dev/null
+++ b/crates/backend-uzu/src/inference_backend.rs
@@ -0,0 +1,30 @@
+use serde::{Deserialize, Serialize};
+use shoji::traits::BackendInstance as BackendInstanceTrait;
+
+use crate::TOOLCHAIN_VERSION;
+
+#[derive(Debug, thiserror::Error)]
+pub enum Error {}
+
+#[derive(Debug, Clone, PartialEq, Eq, Hash, Serialize, Deserialize)]
+pub struct Config;
+
+pub struct Backend;
+
+impl BackendInstanceTrait for Backend {
+ type Error = Error;
+ type Config = Config;
+
+ fn identifier(&self) -> String {
+ "uzu".to_string()
+ }
+
+ fn version(&self) -> String {
+ TOOLCHAIN_VERSION.to_string()
+ }
+
+ #[allow(unused_variables)]
+ fn new(config: Self::Config) -> Result<Self, Self::Error> {
+ Ok(Self)
+ }
+}
diff --git a/crates/backend-uzu/src/lib.rs b/crates/backend-uzu/src/lib.rs
index 759e25b93..ebd122ad6 100644
--- a/crates/backend-uzu/src/lib.rs
+++ b/crates/backend-uzu/src/lib.rs
@@ -8,6 +8,7 @@ mod config;
mod data_type;
mod encodable_block;
mod forward_pass;
+pub mod inference_backend;
mod language_model;
mod parameters;
mod speculators;
@@ -29,4 +30,4 @@ pub use language_model::gumbel::{gumbel_float, revidx};
pub use parameters::{ParameterLoader, read_safetensors_metadata};
#[cfg(feature = "tracing")]
pub use tracer::TraceValidator;
-pub use utils::VERSION;
+pub use utils::{TOOLCHAIN_VERSION, VERSION};
diff --git a/crates/backend-uzu/src/prelude.rs b/crates/backend-uzu/src/prelude.rs
index 7b44d42c4..8a11d1739 100644
--- a/crates/backend-uzu/src/prelude.rs
+++ b/crates/backend-uzu/src/prelude.rs
@@ -14,7 +14,7 @@ pub use crate::backends::metal::MetalContext;
#[cfg(metal_backend)]
pub use crate::session::TtsSession;
pub use crate::{
- VERSION,
+ TOOLCHAIN_VERSION, VERSION,
audio::{AudioCodecRuntime, AudioError, AudioPcmBatch, AudioResult, AudioTokenGrid},
classifier::{ClassificationOutput, ClassificationStats},
parameters::{HeaderLoadingError, ParameterLeaf, ParameterLoaderError, ParameterTree},
@@ -26,5 +26,9 @@ pub use crate::{
Error, FinishReason, Input, Message, Output, ParsedText, Role, RunStats, Stats, StepStats, Text, TotalStats,
},
},
- speculators::{empty_speculator::EmptySpeculator, ngram_speculator::NGramSpeculator, speculator::Speculator},
+ speculators::{
+ empty_speculator::EmptySpeculator, fixed_token_speculator::FixedTokensSpeculator,
+ ngram_speculator::NGramSpeculator, prompt_lookup_speculator::PromptLookupSpeculator, speculator::Speculator,
+ token_finder::TokenFinder,
+ },
};
diff --git a/crates/backend-uzu/src/speculators/fixed_token_speculator.rs b/crates/backend-uzu/src/speculators/fixed_token_speculator.rs
new file mode 100644
index 000000000..5a5a21212
--- /dev/null
+++ b/crates/backend-uzu/src/speculators/fixed_token_speculator.rs
@@ -0,0 +1,49 @@
+use std::collections::HashMap;
+
+use itertools::Itertools;
+
+use crate::speculators::speculator::Speculator;
+
+pub struct FixedTokensSpeculator {
+ tokens: Vec<Vec<u64>>,
+}
+
+impl FixedTokensSpeculator {
+ pub fn new(tokens: Vec<Vec<u64>>) -> Self {
+ Self {
+ tokens,
+ }
+ }
+
+ pub fn max_trie_nodes(&self) -> usize {
+ self.tokens.iter().flat_map(|sequence| (0..=sequence.len()).map(|len| &sequence[..len])).unique().count()
+ }
+}
+
+impl Speculator for FixedTokensSpeculator {
+ fn speculate(
+ &self,
+ prefix: &[u64],
+ ) -> HashMap<u64, f32> {
+ let last_prefix_token = prefix.last().copied();
+ let mut plausible_tokens = HashMap::new();
+
+ for proposed_seq in &self.tokens {
+ let mut proposal_index = 0;
+
+ for (index, &token) in proposed_seq.iter().enumerate() {
+ if last_prefix_token == Some(token) {
+ proposal_index = index + 1;
+ break;
+ }
+ }
+
+ if let Some(&proposed_token) = proposed_seq.get(proposal_index).or(proposed_seq.first()) {
+ *plausible_tokens.entry(proposed_token).or_insert(0.0) += 1.0
+ }
+ }
+
+ let sum: f32 = plausible_tokens.values().sum();
+ plausible_tokens.into_iter().map(|(k, v)| (k, v / sum)).collect()
+ }
+}
diff --git a/crates/backend-uzu/src/speculators/mod.rs b/crates/backend-uzu/src/speculators/mod.rs
index 65e563276..e61f3e1b9 100644
--- a/crates/backend-uzu/src/speculators/mod.rs
+++ b/crates/backend-uzu/src/speculators/mod.rs
@@ -1,3 +1,6 @@
pub mod empty_speculator;
+pub mod fixed_token_speculator;
pub mod ngram_speculator;
+pub mod prompt_lookup_speculator;
pub mod speculator;
+pub mod token_finder;
diff --git a/crates/backend-uzu/src/speculators/prompt_lookup_speculator.rs b/crates/backend-uzu/src/speculators/prompt_lookup_speculator.rs
new file mode 100644
index 000000000..439bf3bde
--- /dev/null
+++ b/crates/backend-uzu/src/speculators/prompt_lookup_speculator.rs
@@ -0,0 +1,42 @@
+use std::collections::HashMap;
+
+use crate::speculators::{speculator::Speculator, token_finder::TokenFinder};
+
+pub struct PromptLookupSpeculator {
+ max_ngram_size: usize,
+}
+
+impl Default for PromptLookupSpeculator {
+ fn default() -> Self {
+ Self::new()
+ }
+}
+
+impl PromptLookupSpeculator {
+ pub fn new() -> Self {
+ Self {
+ max_ngram_size: 3,
+ }
+ }
+
+ pub fn new_with_params(max_ngram_size: usize) -> Self {
+ Self {
+ max_ngram_size,
+ }
+ }
+}
+
+impl Speculator for PromptLookupSpeculator {
+ fn speculate(
+ &self,
+ prefix: &[u64],
+ ) -> HashMap<u64, f32> {
+ let mut hm = HashMap::new();
+
+ if let Some(tok) = TokenFinder::find_candidate_pred_token(prefix, self.max_ngram_size) {
+ hm.insert(tok, 1.0);
+ }
+
+ hm
+ }
+}
diff --git a/crates/backend-uzu/src/speculators/token_finder.rs b/crates/backend-uzu/src/speculators/token_finder.rs
new file mode 100644
index 000000000..4769354e9
--- /dev/null
+++ b/crates/backend-uzu/src/speculators/token_finder.rs
@@ -0,0 +1,34 @@
+pub struct TokenFinder;
+
+impl TokenFinder {
+ pub fn find_candidate_pred_token(
+ sequence: &[u64],
+ max_ngram_size: usize,
+ ) -> Option<u64> {
+ let input_length = sequence.len();
+
+ for ngram_size in (1..=max_ngram_size).rev() {
+ if ngram_size >= input_length {
+ continue;
+ }
+
+ let ngram_start = input_length - ngram_size;
+ let ngram = &sequence[ngram_start..input_length];
+
+ let max_start_index = input_length - ngram_size;
+ for window_start in 0..max_start_index {
+ let window = &sequence[window_start..(window_start + ngram_size)];
+
+ if window == ngram {
+ let start_idx = window_start + ngram_size;
+
+ if start_idx < (input_length - ngram_size) {
+ return Some(sequence[start_idx]);
+ }
+ }
+ }
+ }
+
+ None
+ }
+}
diff --git a/crates/backend-uzu/src/utils/mod.rs b/crates/backend-uzu/src/utils/mod.rs
index 35259d2f2..56db3575d 100644
--- a/crates/backend-uzu/src/utils/mod.rs
+++ b/crates/backend-uzu/src/utils/mod.rs
@@ -6,4 +6,4 @@ pub mod model_size;
pub mod pointers;
pub mod version;
-pub use version::VERSION;
+pub use version::{TOOLCHAIN_VERSION, VERSION};
diff --git a/crates/backend-uzu/src/utils/version.rs b/crates/backend-uzu/src/utils/version.rs
index 9d8f5293c..aacab5d53 100644
--- a/crates/backend-uzu/src/utils/version.rs
+++ b/crates/backend-uzu/src/utils/version.rs
@@ -1 +1,2 @@
pub const VERSION: &str = env!("CARGO_PKG_VERSION");
+pub const TOOLCHAIN_VERSION: &str = "0.6.12";
diff --git a/crates/backend-uzu/tests/integration/session/chat_session/text_session_test.rs b/crates/backend-uzu/tests/integration/session/chat_session/text_session_test.rs
index dd9550144..f200c7271 100644
--- a/crates/backend-uzu/tests/integration/session/chat_session/text_session_test.rs
+++ b/crates/backend-uzu/tests/integration/session/chat_session/text_session_test.rs
@@ -1,12 +1,19 @@
#![cfg(metal_backend)]
-use backend_uzu::session::{
- Session,
- config::{DecodingConfig, RunConfig},
- parameter::SamplingSeed,
- types::{Input, Message, Output},
+use std::sync::Arc;
+
+use backend_uzu::{
+ prelude::{FixedTokensSpeculator, PromptLookupSpeculator, SpeculatorConfig},
+ session::{
+ Session,
+ config::{DecodingConfig, RunConfig},
+ parameter::SamplingSeed,
+ types::{Input, Message, Output},
+ },
};
+use shoji::types::ClassificationFeature;
use test_tag::tag;
+use tokenizers::Tokenizer;
use crate::common::path::get_test_model_path;
@@ -24,6 +31,67 @@ fn test_text_session_base() {
run(build_default_text(), build_decoding_config(), 128);
}
+#[tag(heavy)]
+#[test]
+fn test_text_session_with_prompt_lookup_speculator() {
+ let number_of_speculated_tokens = 16 - 1;
+ let speculator = PromptLookupSpeculator::new_with_params(3);
+ let speculator_config = SpeculatorConfig {
+ number_of_speculated_tokens,
+ speculator: Arc::new(speculator),
+ };
+ let decoding_config = build_decoding_config().with_speculator_config(speculator_config);
+
+ let text_to_summarize = "A Large Language Model (LLM) is a type of artificial intelligence that processes and generates human-like text. It is trained on vast datasets containing books, articles, and web content, allowing it to understand and predict language patterns. LLMs use deep learning, particularly transformer-based architectures, to analyze text, recognize context, and generate coherent responses. These models have a wide range of applications, including chatbots, content creation, translation, and code generation. One of the key strengths of LLMs is their ability to generate contextually relevant text based on prompts. They utilize self-attention mechanisms to weigh the importance of words within a sentence, improving accuracy and fluency. Examples of popular LLMs include OpenAI's GPT series, Google's BERT, and Meta's LLaMA. As these models grow in size and sophistication, they continue to enhance human-computer interactions, making AI-powered communication more natural and effective.";
+ let text = format!("Text is: \"{}\". Write only summary itself.", text_to_summarize);
+
+ run(text, decoding_config, 256);
+}
+
+#[tag(heavy)]
+#[test]
+fn test_text_session_with_fixed_speculator() {
+ let tokenizer = Tokenizer::from_file(get_test_model_path().join("tokenizer.json")).unwrap();
+
+ let feature = ClassificationFeature {
+ name: String::from("sentiment"),
+ values: vec!["Happy", "Sad", "Angry", "Fearful", "Surprised", "Disgusted"]
+ .into_iter()
+ .map(String::from)
+ .collect(),
+ };
+ let proposals: Vec<Vec<u64>> = feature
+ .values
+ .iter()
+ .map(|value| {
+ tokenizer.encode(value.clone().as_str(), false).unwrap().get_ids().iter().map(|&id| id as u64).collect()
+ })
+ .collect();
+ let speculator = FixedTokensSpeculator::new(proposals);
+ let speculator_config = SpeculatorConfig {
+ number_of_speculated_tokens: speculator.max_trie_nodes(),
+ speculator: Arc::new(speculator),
+ };
+ let decoding_config = build_decoding_config().with_speculator_config(speculator_config);
+
+ let text_to_detect_feature = "Today's been awesome! Everything just feels right, and I can't stop smiling.";
+ let text = format!(
+ "Text is: \"{}\". Choose {} from the list: {}. Answer with one word. Dont't add dot at the end.",
+ text_to_detect_feature,
+ feature.name,
+ feature.values.join(", ")
+ );
+
+ run(text, decoding_config, 32);
+}
+
+#[ignore]
+#[tag(heavy)]
+#[test]
+fn test_text_session_ngram_speculator_chat() {
+ todo!("Implement test_text_session_ngram_speculator_chat")
+}
+
#[tag(heavy)]
#[test]
fn test_text_session_scenario() {
diff --git a/crates/backend-uzu/tests/integration/session/mod.rs b/crates/backend-uzu/tests/integration/session/mod.rs
index 8ff40c3ad..7c73b158e 100644
--- a/crates/backend-uzu/tests/integration/session/mod.rs
+++ b/crates/backend-uzu/tests/integration/session/mod.rs
@@ -1,3 +1,4 @@
mod chat_session;
mod config;
+mod speculator;
mod tts_session;
diff --git a/crates/backend-uzu/tests/integration/session/speculator/fixed_token.rs b/crates/backend-uzu/tests/integration/session/speculator/fixed_token.rs
new file mode 100644
index 000000000..0aee1ab61
--- /dev/null
+++ b/crates/backend-uzu/tests/integration/session/speculator/fixed_token.rs
@@ -0,0 +1,34 @@
+use std::collections::HashMap;
+
+use backend_uzu::prelude::{FixedTokensSpeculator, Speculator};
+
+#[test]
+fn test_fixed_token_speculator_single() {
+ let speculator = FixedTokensSpeculator::new(vec![vec![0, 1, 2, 3, 4]]);
+
+ assert_eq!(speculator.speculate(&[]), HashMap::from([(0, 1.0)]));
+ assert_eq!(speculator.speculate(&[1337]), HashMap::from([(0, 1.0)]));
+
+ assert_eq!(speculator.speculate(&[0]), HashMap::from([(1, 1.0)]));
+
+ assert_eq!(speculator.speculate(&[0, 1]), HashMap::from([(2, 1.0)]));
+ assert_eq!(speculator.speculate(&[1]), HashMap::from([(2, 1.0)]));
+
+ assert_eq!(speculator.speculate(&[4]), HashMap::from([(0, 1.0)]));
+}
+
+#[test]
+fn test_fixed_token_speculator_multi() {
+ let speculator =
+ FixedTokensSpeculator::new(vec![vec![0, 1, 2, 3, 4], vec![0, 1, 2, 4, 8], vec![0, 10, 20, 30, 40]]);
+
+ assert_eq!(speculator.speculate(&[]), HashMap::from([(0, 1.0)]));
+ assert_eq!(speculator.speculate(&[1337]), HashMap::from([(0, 1.0)]));
+
+ assert_eq!(speculator.speculate(&[0]), HashMap::from([(1, 2.0 / 3.0), (10, 1.0 / 3.0)]));
+
+ assert_eq!(speculator.speculate(&[0, 1]), HashMap::from([(0, 1.0 / 3.0), (2, 2.0 / 3.0)]));
+ assert_eq!(speculator.speculate(&[1]), HashMap::from([(0, 1.0 / 3.0), (2, 2.0 / 3.0)]));
+
+ assert_eq!(speculator.speculate(&[4]), HashMap::from([(8, 1.0 / 3.0), (0, 2.0 / 3.0)]));
+}
diff --git a/crates/backend-uzu/tests/integration/session/speculator/mod.rs b/crates/backend-uzu/tests/integration/session/speculator/mod.rs
new file mode 100644
index 000000000..3464b58dd
--- /dev/null
+++ b/crates/backend-uzu/tests/integration/session/speculator/mod.rs
@@ -0,0 +1,3 @@
+mod fixed_token;
+mod prompt_lookup;
+mod token_finder;
diff --git a/crates/backend-uzu/tests/integration/session/speculator/prompt_lookup.rs b/crates/backend-uzu/tests/integration/session/speculator/prompt_lookup.rs
new file mode 100644
index 000000000..5028ec5e2
--- /dev/null
+++ b/crates/backend-uzu/tests/integration/session/speculator/prompt_lookup.rs
@@ -0,0 +1,62 @@
+use std::collections::HashMap;
+
+use backend_uzu::prelude::{PromptLookupSpeculator, Speculator};
+use tokenizers::Tokenizer;
+
+use crate::common::path::get_test_model_path;
+
+fn load_tokenizer() -> Tokenizer {
+ let tokenizer_path = get_test_model_path().join("tokenizer.json");
+ match Tokenizer::from_file(tokenizer_path) {
+ Ok(tokenizer) => tokenizer,
+ Err(e) => {
+ panic!("Failed to load tokenizer: {}", e);
+ },
+ }
+}
+
+fn tokenize_text(
+ tokenizer: &Tokenizer,
+ text: &str,
+) -> Vec<u64> {
+ let encoding = tokenizer.encode(text, false).expect("Failed to encode text");
+ encoding.get_ids().iter().map(|&id| id as u64).collect()
+}
+
+#[test]
+fn test_empty_input() {
+ let speculator = PromptLookupSpeculator::new();
+ let prefix: Vec<u64> = vec![];
+
+ let proposals = speculator.speculate(&prefix);
+
+ assert_eq!(proposals.len(), 0);
+}
+
+#[test]
+fn test_no_pattern_found() {
+ let speculator = PromptLookupSpeculator::new();
+ let prefix = vec![1, 2, 3, 4, 5, 6, 7, 8, 9];
+
+ let proposals = speculator.speculate(&prefix);
+
+ assert_eq!(proposals.len(), 0);
+}
+
+#[test]
+fn test_with_real_text() {
+ let tokenizer = load_tokenizer();
+ let speculator = PromptLookupSpeculator::new_with_params(3);
+
+ let text = "The quick brown fox jumps over the lazy dog. The quick brown fox";
+
+ let mut tokens = tokenize_text(&tokenizer, text);
+
+ for expected in tokenize_text(&tokenizer, " jumps over the lazy dog") {
+ let proposals = speculator.speculate(&tokens);
+
+ assert_eq!(proposals, HashMap::from([(expected, 1.0)]));
+
+ tokens.push(expected);
+ }
+}
diff --git a/crates/backend-uzu/tests/integration/session/speculator/token_finder.rs b/crates/backend-uzu/tests/integration/session/speculator/token_finder.rs
new file mode 100644
index 000000000..f4880a5f9
--- /dev/null
+++ b/crates/backend-uzu/tests/integration/session/speculator/token_finder.rs
@@ -0,0 +1,101 @@
+use backend_uzu::prelude::TokenFinder;
+
+#[test]
+fn test_find_candidate_pred_token_empty_sequence() {
+ let sequence: Vec<u64> = vec![];
+
+ let result = TokenFinder::find_candidate_pred_token(&sequence, 3);
+
+ assert!(result.is_none());
+}
+
+#[test]
+fn test_find_candidate_pred_token_sequence_too_short() {
+ let sequence: Vec<u64> = vec![1, 2];
+
+ let result = TokenFinder::find_candidate_pred_token(&sequence, 3);
+
+ assert!(result.is_none());
+}
+
+#[test]
+fn test_find_candidate_pred_token_exact_pattern_match() {
+ let sequence = vec![1, 2, 3, 4, 5, 1, 2, 3];
+
+ let result = TokenFinder::find_candidate_pred_token(&sequence, 3);
+
+ assert_eq!(result, Some(4));
+}
+
+#[test]
+fn test_find_candidate_pred_token_valid_match() {
+ let mut sequence = vec![1, 2, 3, 4, 5, 1, 2, 3];
+
+ let result1 = TokenFinder::find_candidate_pred_token(&sequence, 3);
+
+ assert_eq!(result1, Some(4));
+
+ sequence.push(4);
+
+ let result2 = TokenFinder::find_candidate_pred_token(&sequence, 3);
+
+ assert_eq!(result2, Some(5));
+}
+
+#[test]
+fn test_find_candidate_pred_token_multiple_matches() {
+ let mut sequence = vec![1, 2, 3, 4, 5, 1, 2, 3, 6, 7, 1, 2, 3];
+
+ let result1 = TokenFinder::find_candidate_pred_token(&sequence, 3);
+
+ assert_eq!(result1, Some(4));
+ assert_ne!(result1, Some(6));
+
+ sequence.push(4);
+
+ let result2 = TokenFinder::find_candidate_pred_token(&sequence, 3);
+
+ assert_eq!(result2, Some(5));
+ assert_ne!(result2, Some(7));
+}
+
+#[test]
+fn test_find_candidate_pred_token_different_ngram_sizes() {
+ let mut sequence = vec![1, 2, 3, 4, 5, 1, 2, 3, 8, 9, 1, 2, 3, 4, 5];
+
+ let result1_3 = TokenFinder::find_candidate_pred_token(&sequence, 3);
+ let result1_2 = TokenFinder::find_candidate_pred_token(&sequence, 2);
+ let result1_1 = TokenFinder::find_candidate_pred_token(&sequence, 1);
+
+ assert_eq!(result1_3, Some(1));
+ assert_eq!(result1_2, Some(1));
+ assert_eq!(result1_1, Some(1));
+
+ sequence.push(1);
+
+ let result2_3 = TokenFinder::find_candidate_pred_token(&sequence, 3);
+ let result2_2 = TokenFinder::find_candidate_pred_token(&sequence, 2);
+ let result2_1 = TokenFinder::find_candidate_pred_token(&sequence, 1);
+
+ assert_eq!(result2_3, Some(2));
+ assert_eq!(result2_2, Some(2));
+ assert_eq!(result2_1, Some(2));
+}
+
+#[test]
+fn test_find_candidate_pred_token_no_match() {
+ let sequence = vec![1, 2, 3, 4, 5, 6, 7, 8, 9];
+
+ let result = TokenFinder::find_candidate_pred_token(&sequence, 3);
+
+ assert!(result.is_none());
+}
+
+#[test]
+fn test_find_candidate_pred_token_max_ngram_higher_than_input() {
+ let sequence = vec![1, 2, 3, 4, 5];
+
+ let result = TokenFinder::find_candidate_pred_token(&sequence, 8);
+
+ assert!(result.is_none());
+}
diff --git a/crates/cli-storage/Cargo.toml b/crates/cli-storage/Cargo.toml
new file mode 100644
index 000000000..e682bef33
--- /dev/null
+++ b/crates/cli-storage/Cargo.toml
@@ -0,0 +1,24 @@
+[package]
+name = "cli-storage"
+version.workspace = true
+edition.workspace = true
+rust-version.workspace = true
+license.workspace = true
+authors.workspace = true
+repository.workspace = true
+
+[[bin]]
+name = "cli-storage"
+path = "src/main.rs"
+
+[dependencies]
+shoji.workspace = true
+uzu.workspace = true
+tokio.workspace = true
+futures-util.workspace = true
+crossterm.workspace = true
+ratatui.workspace = true
+tracing.workspace = true
+tracing-subscriber.workspace = true
+tracing-appender.workspace = true
+dotenvy.workspace = true
diff --git a/crates/cli-storage/src/app.rs b/crates/cli-storage/src/app.rs
new file mode 100644
index 000000000..6d98832db
--- /dev/null
+++ b/crates/cli-storage/src/app.rs
@@ -0,0 +1,296 @@
+use std::{collections::HashMap, sync::Arc};
+
+use crossterm::event::KeyCode;
+use futures_util::StreamExt;
+use ratatui::widgets::ListState;
+use shoji::types::Model;
+use tokio::{sync::Mutex as TokioMutex, task::JoinHandle};
+use uzu::{engine::Engine, storage::types::DownloadState};
+
+use crate::{events::AppEvent, models::ModelOrganizer, sections::Section};
+
+/// Holds a Model handle and its cached state for UI rendering
+#[derive(Clone)]
+pub struct ModelWithState {
+ pub model: Model,
+ pub state: DownloadState,
+}
+
+pub struct App {
+ pub engine: Arc<Engine>,
+ pub models: Arc<TokioMutex<HashMap<String, ModelWithState>>>,
+ pub active_section: Section,
+ pub list_states: HashMap<Section, ListState>,
+ pub should_quit: bool,
+ state_listener_handle: Arc<TokioMutex<Option<JoinHandle<()>>>>,
+ tokio_handle: tokio::runtime::Handle,
+}
+
+impl App {
+ pub async fn new(
+ engine: Arc<Engine>,
+ tokio_handle: tokio::runtime::Handle,
+ ) -> Self {
+ let models = engine.models().await.unwrap().into_iter().filter(|model| model.is_local()).collect::<Vec<_>>();
+
+ // Fetch initial state for all models
+ let mut models_with_state = HashMap::new();
+ for model in models {
+ let state = engine.downloader(&model).state().await.unwrap();
+ models_with_state.insert(
+ model.identifier(),
+ ModelWithState {
+ model,
+ state,
+ },
+ );
+ }
+
+ let mut list_states = HashMap::new();
+ for section in Section::all() {
+ list_states.insert(section, ListState::default());
+ }
+
+ Self {
+ engine,
+ models: Arc::new(TokioMutex::new(models_with_state)),
+ active_section: Section::Available,
+ list_states,
+ should_quit: false,
+ state_listener_handle: Arc::new(TokioMutex::new(None)),
+ tokio_handle,
+ }
+ }
+
+ /// Spawn a background task that listens to model state updates
+ pub async fn spawn_state_listener(&mut self) {
+ let models = Arc::clone(&self.models);
+ let engine = Arc::clone(&self.engine);
+ let mut updates = self.engine.storage_subscribe().await;
+
+ let handle = self.tokio_handle.spawn(async move {
+ while let Some(Ok((model_id, state))) = updates.next().await {
+ let mut models_guard = models.lock().await;
+
+ if let Some(model_with_state) = models_guard.get_mut(&model_id) {
+ // Update the cached state
+ model_with_state.state = state;
+ } else {
+ // Model not in local HashMap; fetch from storage and add it
+ drop(models_guard);
+ if let Some(fresh_model) = engine.model_by_identifier(&model_id).await.unwrap() {
+ let state = engine.downloader(&fresh_model).state().await.unwrap();
+ let mut models_guard = models.lock().await;
+ models_guard.insert(
+ model_id,
+ ModelWithState {
+ model: fresh_model,
+ state,
+ },
+ );
+ }
+ }
+ }
+ });
+
+ *self.state_listener_handle.lock().await = Some(handle);
+ }
+
+ pub async fn handle_event(
+ &mut self,
+ event: AppEvent,
+ ) {
+ match event {
+ AppEvent::Key(key) => match key {
+ KeyCode::Char('q') => self.should_quit = true,
+ KeyCode::Left => self.prev_section(),
+ KeyCode::Right => self.next_section(),
+ KeyCode::Up => self.previous_item().await,
+ KeyCode::Down => self.next_item().await,
+ KeyCode::Char('d') | KeyCode::Enter => self.download_or_resume_selected().await,
+ KeyCode::Char('p') => self.pause_selected().await,
+ KeyCode::Char('x') => self.delete_selected().await,
+ _ => {},
+ },
+ AppEvent::Tick => {},
+ }
+ }
+
+ fn next_section(&mut self) {
+ self.active_section = self.active_section.next();
+ }
+
+ fn prev_section(&mut self) {
+ self.active_section = self.active_section.prev();
+ }
+
+ async fn next_item(&mut self) {
+ let section = self.active_section;
+ let count = {
+ let models = self.models.lock().await;
+ ModelOrganizer::filter_for_section(&models, section).len()
+ };
+
+ if count == 0 {
+ return;
+ }
+
+ if let Some(state) = self.list_states.get_mut(&section) {
+ let i = state.selected().map_or(0, |i| {
+ if i >= count - 1 {
+ count - 1
+ } else {
+ i + 1
+ }
+ });
+ state.select(Some(i));
+ }
+ }
+
+ async fn previous_item(&mut self) {
+ let section = self.active_section;
+ let count = {
+ let models = self.models.lock().await;
+ ModelOrganizer::filter_for_section(&models, section).len()
+ };
+
+ if count == 0 {
+ return;
+ }
+
+ if let Some(state) = self.list_states.get_mut(&section) {
+ let i = state.selected().map_or(0, |i| {
+ if i == 0 {
+ 0
+ } else {
+ i - 1
+ }
+ });
+ state.select(Some(i));
+ }
+ }
+
+ pub fn get_selected_model_id(
+ &self,
+ models: &HashMap<String, ModelWithState>,
+ ) -> Option<String> {
+ let state = self.list_states.get(&self.active_section)?;
+ let selected_idx = state.selected()?;
+ let section_models = ModelOrganizer::filter_for_section(models, self.active_section);
+ section_models.get(selected_idx).map(|(id, _)| id.clone())
+ }
+
+ async fn download_or_resume_selected(&mut self) {
+ let model_id = {
+ let models = self.models.lock().await;
+ self.get_selected_model_id(&models)
+ };
+
+ if let Some(id) = model_id {
+ let models_guard = self.models.lock().await;
+ if let Some(model_with_state) = models_guard.get(&id) {
+ use uzu::storage::types::DownloadPhase::*;
+ match model_with_state.state.phase {
+ Downloaded => {
+ // Already installed; ignore download command
+ },
+ _ => {
+ let _ = self.engine.downloader(&model_with_state.model).resume().await;
+ },
+ }
+ }
+ }
+ }
+
+ async fn pause_selected(&mut self) {
+ let model_id = {
+ let models = self.models.lock().await;
+ self.get_selected_model_id(&models)
+ };
+
+ if let Some(id) = model_id {
+ let models_guard = self.models.lock().await;
+ if let Some(model_with_state) = models_guard.get(&id) {
+ let _ = self.engine.downloader(&model_with_state.model).pause().await;
+ }
+ }
+ }
+
+ async fn delete_selected(&mut self) {
+ let model_id = {
+ let models = self.models.lock().await;
+ self.get_selected_model_id(&models)
+ };
+
+ if let Some(id) = model_id {
+ let models_guard = self.models.lock().await;
+ if let Some(model_with_state) = models_guard.get(&id) {
+ // Can delete from any section: Downloading, Paused, Downloaded, Installed
+ let _ = self.engine.downloader(&model_with_state.model).delete().await;
+ }
+ }
+ }
+
+ /// Get helper text based on current section and selection
+ pub fn get_helpers(
+ &self,
+ models: &HashMap<String, ModelWithState>,
+ ) -> Vec<String> {
+ let selected_model_id = self.get_selected_model_id(models);
+
+ match self.active_section {
+ Section::Available => {
+ if selected_model_id.is_some() {
+ vec![
+ "↑↓: Navigate".to_string(),
+ "←→: Switch section".to_string(),
+ "d/Enter: Download".to_string(),
+ "q: Quit".to_string(),
+ ]
+ } else {
+ vec!["←→: Switch section".to_string(), "q: Quit".to_string()]
+ }
+ },
+ Section::Downloading => {
+ if let Some(_id) = &selected_model_id {
+ // Check if model is paused
+ // Note: This is a synchronous context, so we'll use a blocking approach
+ // In a real scenario, this should be refactored to async
+ let is_paused = false; // Simplified for now - models are dynamic
+
+ if is_paused {
+ vec![
+ "↑↓: Navigate".to_string(),
+ "←→: Switch section".to_string(),
+ "d/Enter: Resume".to_string(),
+ "x: Delete".to_string(),
+ "q: Quit".to_string(),
+ ]
+ } else {
+ vec![
+ "↑↓: Navigate".to_string(),
+ "←→: Switch section".to_string(),
+ "p: Pause".to_string(),
+ "x: Delete".to_string(),
+ "q: Quit".to_string(),
+ ]
+ }
+ } else {
+ vec!["←→: Switch section".to_string(), "q: Quit".to_string()]
+ }
+ },
+ Section::Installed => {
+ if selected_model_id.is_some() {
+ vec![
+ "↑↓: Navigate".to_string(),
+ "←→: Switch section".to_string(),
+ "x: Delete".to_string(),
+ "q: Quit".to_string(),
+ ]
+ } else {
+ vec!["←→: Switch section".to_string(), "q: Quit".to_string()]
+ }
+ },
+ }
+ }
+}
diff --git a/crates/cli-storage/src/events.rs b/crates/cli-storage/src/events.rs
new file mode 100644
index 000000000..e358dd4b3
--- /dev/null
+++ b/crates/cli-storage/src/events.rs
@@ -0,0 +1,36 @@
+use std::{io, time::Duration};
+
+use crossterm::event::{self, Event, KeyCode};
+
+pub struct EventHandler {
+ last_event: Option<AppEvent>,
+}
+
+#[derive(Debug, Clone)]
+pub enum AppEvent {
+ Key(KeyCode),
+ #[allow(dead_code)]
+ Tick,
+}
+
+impl EventHandler {
+ pub fn new() -> Self {
+ Self {
+ last_event: None,
+ }
+ }
+
+ pub async fn poll_event(&mut self) -> io::Result<bool> {
+ if event::poll(Duration::from_millis(100))? {
+ if let Event::Key(key) = event::read()? {
+ self.last_event = Some(AppEvent::Key(key.code));
+ return Ok(true);
+ }
+ }
+ Ok(false)
+ }
+
+ pub fn next_event(&mut self) -> Option<AppEvent> {
+ self.last_event.take()
+ }
+}
diff --git a/crates/cli-storage/src/main.rs b/crates/cli-storage/src/main.rs
new file mode 100644
index 000000000..0628fe196
--- /dev/null
+++ b/crates/cli-storage/src/main.rs
@@ -0,0 +1,81 @@
+#![cfg(target_os = "macos")]
+
+mod app;
+mod events;
+mod models;
+mod sections;
+mod ui;
+
+use std::{io, sync::Arc};
+
+use crossterm::{
+ execute,
+ terminal::{EnterAlternateScreen, LeaveAlternateScreen, disable_raw_mode, enable_raw_mode},
+};
+use ratatui::{Terminal, backend::CrosstermBackend};
+use uzu::engine::{Config as EngineConfig, Engine};
+
+use crate::{app::App, events::EventHandler};
+
+#[tokio::main]
+async fn main() -> Result<(), Box<dyn std::error::Error>> {
+ dotenvy::dotenv().ok();
+ let runtime = tokio::runtime::Handle::current();
+ let engine = Arc::new(Engine::new(EngineConfig::default()).await?);
+
+ // Setup terminal
+ enable_raw_mode()?;
+ let mut stdout = io::stdout();
+ execute!(stdout, EnterAlternateScreen)?;
+ let backend = CrosstermBackend::new(stdout);
+ let mut terminal = Terminal::new(backend)?;
+
+ // Create app and event handler
+ let app = App::new(engine.clone(), runtime).await;
+ let event_handler = EventHandler::new();
+
+ // Run app
+ let res = run_app(&mut terminal, app, event_handler).await;
+
+ // Cleanup
+ disable_raw_mode()?;
+ execute!(terminal.backend_mut(), LeaveAlternateScreen)?;
+ terminal.show_cursor()?;
+
+ if let Err(e) = res {
+ tracing::error!("Application error: {:?}", e);
+ }
+
+ Ok(())
+}
+
+async fn run_app<B: ratatui::backend::Backend>(
+ terminal: &mut Terminal<B>,
+ mut app: App,
+ mut event_handler: EventHandler,
+) -> io::Result<()> {
+ // Spawn model state listener
+ app.spawn_state_listener().await;
+
+ loop {
+ terminal
+ .draw(|f| ui::draw(f, &mut app))
+ .map_err(|error| io::Error::new(io::ErrorKind::Other, error.to_string()))?;
+
+ if app.should_quit {
+ break;
+ }
+
+ // Handle events
+ if event_handler.poll_event().await? {
+ if let Some(event) = event_handler.next_event() {
+ app.handle_event(event).await;
+ }
+ }
+
+ // Small delay to reduce CPU usage
+ tokio::time::sleep(std::time::Duration::from_millis(50)).await;
+ }
+
+ Ok(())
+}
diff --git a/crates/cli-storage/src/models.rs b/crates/cli-storage/src/models.rs
new file mode 100644
index 000000000..0b0934ce4
--- /dev/null
+++ b/crates/cli-storage/src/models.rs
@@ -0,0 +1,26 @@
+use std::collections::HashMap;
+
+use crate::{app::ModelWithState, sections::Section};
+
+pub struct ModelOrganizer;
+
+impl ModelOrganizer {
+ /// Filter models for a specific section
+ pub fn filter_for_section(
+ models: &HashMap<String, ModelWithState>,
+ section: Section,
+ ) -> Vec<(String, ModelWithState)> {
+ let mut filtered: Vec<(String, ModelWithState)> = models
+ .iter()
+ .filter(|(_, model_with_state)| {
+ let model_section = Section::for_model(model_with_state);
+ model_section == section
+ })
+ .map(|(id, model_with_state)| (id.clone(), model_with_state.clone()))
+ .collect();
+
+ // Sort by identifier
+ filtered.sort_by(|a, b| a.0.cmp(&b.0));
+ filtered
+ }
+}
diff --git a/crates/cli-storage/src/sections.rs b/crates/cli-storage/src/sections.rs
new file mode 100644
index 000000000..5951f7447
--- /dev/null
+++ b/crates/cli-storage/src/sections.rs
@@ -0,0 +1,51 @@
+use uzu::storage::types::DownloadPhase;
+
+use crate::app::ModelWithState;
+
+#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
+pub enum Section {
+ Installed,
+ Downloading,
+ Available,
+}
+
+impl Section {
+ pub fn next(&self) -> Self {
+ match self {
+ Section::Installed => Section::Downloading,
+ Section::Downloading => Section::Available,
+ Section::Available => Section::Installed,
+ }
+ }
+
+ pub fn prev(&self) -> Self {
+ match self {
+ Section::Installed => Section::Available,
+ Section::Downloading => Section::Installed,
+ Section::Available => Section::Downloading,
+ }
+ }
+
+ pub fn title(&self) -> &'static str {
+ match self {
+ Section::Installed => "Installed",
+ Section::Downloading => "Downloading",
+ Section::Available => "Available",
+ }
+ }
+
+ /// Determine which section a model belongs to based on its state
+ pub fn for_model(model_with_state: &ModelWithState) -> Self {
+ match model_with_state.state.phase {
+ DownloadPhase::Downloaded => Section::Installed,
+ DownloadPhase::Downloading | DownloadPhase::Paused | DownloadPhase::Locked | DownloadPhase::Error(_) => {
+ Section::Downloading
+ },
+ DownloadPhase::NotDownloaded => Section::Available,
+ }
+ }
+
+ pub fn all() -> [Section; 3] {
+ [Section::Installed, Section::Downloading, Section::Available]
+ }
+}
diff --git a/crates/cli-storage/src/ui.rs b/crates/cli-storage/src/ui.rs
new file mode 100644
index 000000000..72624be0a
--- /dev/null
+++ b/crates/cli-storage/src/ui.rs
@@ -0,0 +1,312 @@
+use ratatui::{
+ layout::{Constraint, Direction, Layout, Rect},
+ prelude::Frame,
+ style::{Color, Modifier, Style},
+ widgets::{Block, Borders, Gauge, List, ListItem, Paragraph},
+};
+
+use crate::{
+ app::{App, ModelWithState},
+ models::ModelOrganizer,
+ sections::Section,
+};
+
+pub fn draw(
+ frame: &mut Frame,
+ app: &mut App,
+) {
+ // Try to get models snapshot
+ let models_snapshot = match app.models.try_lock() {
+ Ok(guard) => guard.clone(),
+ Err(_) => return, // Skip frame if locked
+ };
+
+ // Main layout
+ let chunks = Layout::default()
+ .direction(Direction::Vertical)
+ .constraints([Constraint::Min(0), Constraint::Length(3)])
+ .split(frame.area());
+
+ // Three columns for sections
+ let main_chunks = Layout::default()
+ .direction(Direction::Horizontal)
+ .constraints([Constraint::Percentage(33), Constraint::Percentage(33), Constraint::Percentage(34)])
+ .split(chunks[0]);
+
+ // Render each section
+ render_section(frame, main_chunks[0], app, &models_snapshot, Section::Installed);
+ render_section(frame, main_chunks[1], app, &models_snapshot, Section::Downloading);
+ render_section(frame, main_chunks[2], app, &models_snapshot, Section::Available);
+
+ // Render contextual help
+ render_help(frame, chunks[1], app, &models_snapshot);
+}
+
+fn render_section(
+ frame: &mut Frame,
+ area: Rect,
+ app: &mut App,
+ models: &std::collections::HashMap<String, ModelWithState>,
+ section: Section,
+) {
+ let is_active = app.active_section == section;
+ let section_models = ModelOrganizer::filter_for_section(models, section);
+
+ // Special rendering for Downloading section with progress
+ if section == Section::Downloading && !section_models.is_empty() {
+ render_downloading_section(frame, area, app, &section_models, is_active);
+ return;
+ }
+
+ // Regular list rendering
+ let items: Vec<ListItem> = section_models
+ .iter()
+ .map(|(id, model_with_state)| match &model_with_state.state.phase {
+ uzu::storage::types::DownloadPhase::Downloaded => ListItem::new(format!("✓ {}", id)),
+ uzu::storage::types::DownloadPhase::NotDownloaded => {
+ let size_mb = model_with_state.state.total_bytes as f64 / 1_000_000.0;
+ ListItem::new(format!("{} ({:.1} MB)", id, size_mb))
+ },
+ _ => ListItem::new(id.clone()),
+ })
+ .collect();
+
+ let (border_style, highlight_style) = if is_active {
+ (
+ Style::default().fg(Color::Cyan).add_modifier(Modifier::BOLD),
+ Style::default().bg(Color::Blue).fg(Color::White).add_modifier(Modifier::BOLD),
+ )
+ } else {
+ (Style::default().fg(Color::Gray), Style::default().bg(Color::DarkGray))
+ };
+
+ let list = List::new(items)
+ .block(
+ Block::default()
+ .borders(Borders::ALL)
+ .title(format!("{} ({})", section.title(), section_models.len()))
+ .border_style(border_style),
+ )
+ .highlight_style(highlight_style);
+
+ // Update list state
+ let state = app.list_states.get_mut(&section).unwrap();
+
+ if section_models.is_empty() {
+ state.select(None);
+ } else if state.selected().is_none() {
+ state.select(Some(0));
+ } else if let Some(selected) = state.selected() {
+ if selected >= section_models.len() {
+ state.select(Some(section_models.len().saturating_sub(1)));
+ }
+ }
+
+ frame.render_stateful_widget(list, area, state);
+}
+
+fn render_downloading_section(
+ frame: &mut Frame,
+ area: Rect,
+ app: &mut App,
+ section_models: &[(String, ModelWithState)],
+ is_active: bool,
+) {
+ let border_style = if is_active {
+ Style::default().fg(Color::Cyan).add_modifier(Modifier::BOLD)
+ } else {
+ Style::default().fg(Color::Gray)
+ };
+
+ let block = Block::default()
+ .borders(Borders::ALL)
+ .title(format!("Downloading ({})", section_models.len()))
+ .border_style(border_style);
+
+ let inner = block.inner(area);
+ frame.render_widget(block, area);
+
+ // Calculate layout for each model
+ let model_height = 3;
+ let available_height = inner.height as usize;
+ let visible_count = (available_height / model_height).min(section_models.len());
+
+ let state = app.list_states.get_mut(&Section::Downloading).unwrap();
+ let selected = state.selected().unwrap_or(0);
+
+ // Scroll to keep selection visible
+ let scroll_offset = if selected >= visible_count {
+ selected - visible_count + 1
+ } else {
+ 0
+ };
+
+ let constraints: Vec<Constraint> = (0..visible_count).map(|_| Constraint::Length(model_height as u16)).collect();
+
+ if constraints.is_empty() {
+ return;
+ }
+
+ let model_chunks = Layout::default().direction(Direction::Vertical).constraints(constraints).split(inner);
+
+ // Render visible models
+ for (i, chunk) in model_chunks.iter().enumerate() {
+ let model_idx = i + scroll_offset;
+ if model_idx >= section_models.len() {
+ break;
+ }
+
+ let (id, model_with_state) = &section_models[model_idx];
+ let is_selected = model_idx == selected;
+
+ render_downloading_model(frame, *chunk, id, model_with_state, is_selected);
+ }
+}
+
+fn render_downloading_model(
+ frame: &mut Frame,
+ area: Rect,
+ id: &str,
+ model_with_state: &ModelWithState,
+ is_selected: bool,
+) {
+ let progress = model_with_state.state.progress() as f64;
+ let downloaded_mb = model_with_state.state.downloaded_bytes as f64 / 1_000_000.0;
+ let total_mb = model_with_state.state.total_bytes as f64 / 1_000_000.0;
+
+ // Calculate available width (subtract borders: 2 chars)
+ let available_width = area.width.saturating_sub(2) as usize;
+
+ let (base_label, gauge_color, border_color) = match &model_with_state.state.phase {
+ uzu::storage::types::DownloadPhase::Downloading => {
+ let progress_info = format!(" ({:.1}/{:.1} MB - {:.1}%)", downloaded_mb, total_mb, progress * 100.0);
+ let name = truncate_name_for_label(id, &progress_info, available_width, is_selected);
+ (
+ format!("{}{}", name, progress_info),
+ Color::Cyan,
+ if is_selected {
+ Color::Blue
+ } else {
+ Color::Gray
+ },
+ )
+ },
+ uzu::storage::types::DownloadPhase::Paused => {
+ let progress_info =
+ format!(" [PAUSED] ({:.1}/{:.1} MB - {:.1}%)", downloaded_mb, total_mb, progress * 100.0);
+ let name = truncate_name_for_label(id, &progress_info, available_width, is_selected);
+ (
+ format!("{}{}", name, progress_info),
+ Color::Yellow,
+ if is_selected {
+ Color::Yellow
+ } else {
+ Color::Gray
+ },
+ )
+ },
+ uzu::storage::types::DownloadPhase::Error(err) => {
+ let error_info = format!(" [ERROR: {}]", err);
+ let name = truncate_name_for_label(id, &error_info, available_width, is_selected);
+ (
+ format!("{}{}", name, error_info),
+ Color::Red,
+ if is_selected {
+ Color::Red
+ } else {
+ Color::Gray
+ },
+ )
+ },
+ _ => (
+ truncate_text(id, available_width),
+ Color::Gray,
+ if is_selected {
+ Color::White
+ } else {
+ Color::Gray
+ },
+ ),
+ };
+
+ let label = if is_selected {
+ format!("▶ {}", base_label)
+ } else {
+ base_label
+ };
+
+ let gauge_style = if is_selected {
+ Style::default().fg(Color::White).bg(Color::Blue).add_modifier(Modifier::BOLD)
+ } else {
+ Style::default().fg(gauge_color).bg(Color::Black)
+ };
+
+ let gauge = Gauge::default()
+ .block(Block::default().borders(Borders::ALL).border_style(Style::default().fg(border_color).add_modifier(
+ if is_selected {
+ Modifier::BOLD
+ } else {
+ Modifier::empty()
+ },
+ )))
+ .gauge_style(gauge_style)
+ .label(label)
+ .ratio(progress.min(1.0).max(0.0));
+
+ frame.render_widget(gauge, area);
+}
+
+fn render_help(
+ frame: &mut Frame,
+ area: Rect,
+ app: &App,
+ models: &std::collections::HashMap<String, ModelWithState>,
+) {
+ let helpers = app.get_helpers(models);
+ let help_text = helpers.join(" | ");
+
+ let help = Paragraph::new(help_text)
+ .block(Block::default().borders(Borders::ALL).title("Help"))
+ .style(Style::default().fg(Color::Gray));
+
+ frame.render_widget(help, area);
+}
+
+/// Truncate name to fit with progress info
+fn truncate_name_for_label(
+ name: &str,
+ progress_info: &str,
+ available_width: usize,
+ is_selected: bool,
+) -> String {
+ // Account for selection indicator "▶ " if selected
+ let indicator_len = if is_selected {
+ 2
+ } else {
+ 0
+ };
+ let progress_len = progress_info.len();
+
+ // Calculate max name length
+ let max_name_len = available_width.saturating_sub(indicator_len).saturating_sub(progress_len);
+
+ truncate_text(name, max_name_len)
+}
+
+/// Truncate text to fit within max_len, adding "..." if needed
+fn truncate_text(
+ text: &str,
+ max_len: usize,
+) -> String {
+ if text.len() <= max_len {
+ return text.to_string();
+ }
+
+ if max_len <= 3 {
+ return text.chars().take(max_len).collect();
+ }
+
+ // Reserve 3 chars for "..."
+ let truncate_at = max_len.saturating_sub(3);
+ format!("{}...", text.chars().take(truncate_at).collect::<String>())
+}
diff --git a/crates/hanashi/Cargo.toml b/crates/hanashi/Cargo.toml
index b929e4b06..4b68bb1bc 100644
--- a/crates/hanashi/Cargo.toml
+++ b/crates/hanashi/Cargo.toml
@@ -7,38 +7,9 @@ license.workspace = true
authors.workspace = true
repository.workspace = true
-[lib]
-crate-type = ["lib", "cdylib", "staticlib"]
-
-[features]
-default = []
-bindings = [
- "bindings-uniffi",
- "bindings-napi",
- "bindings-pyo3",
- "bindings-wasm",
-]
-bindings-uniffi = ["dep:uniffi"]
-bindings-napi = ["dep:napi", "dep:napi-derive", "dep:napi-build"]
-bindings-pyo3 = ["dep:pyo3"]
-bindings-wasm = [
- "dep:wasm-bindgen",
- "dep:serde-wasm-bindgen",
- "dep:wasm-bindgen-futures",
- "dep:tsify",
-]
-
[dependencies]
-bindings.workspace = true
+shoji.workspace = true
token-stream-parser.workspace = true
-uniffi = { workspace = true, optional = true }
-napi = { workspace = true, optional = true }
-napi-derive = { workspace = true, optional = true }
-pyo3 = { workspace = true, optional = true }
-wasm-bindgen = { workspace = true, optional = true }
-serde-wasm-bindgen = { workspace = true, optional = true }
-wasm-bindgen-futures = { workspace = true, optional = true }
-tsify = { workspace = true, optional = true }
tokenizers.workspace = true
openai-harmony.workspace = true
serde.workspace = true
@@ -54,4 +25,3 @@ indexmap.workspace = true
[build-dependencies]
serde_json.workspace = true
-napi-build = { workspace = true, optional = true }
diff --git a/crates/hanashi/build.rs b/crates/hanashi/build.rs
index 172ab8bfb..e4b746bcb 100644
--- a/crates/hanashi/build.rs
+++ b/crates/hanashi/build.rs
@@ -14,9 +14,6 @@ fn raw_string_delimiter(content: &str) -> String {
}
fn main() {
- #[cfg(feature = "bindings-napi")]
- napi_build::setup();
-
let manifest_directory = env::var("CARGO_MANIFEST_DIR").unwrap();
let configs_directory = Path::new(&manifest_directory).join("configs");
diff --git a/crates/hanashi/src/chat/encoding/config.rs b/crates/hanashi/src/chat/config.rs
similarity index 78%
rename from crates/hanashi/src/chat/encoding/config.rs
rename to crates/hanashi/src/chat/config.rs
index 70e387dbf..a2fcbd402 100644
--- a/crates/hanashi/src/chat/encoding/config.rs
+++ b/crates/hanashi/src/chat/config.rs
@@ -1,9 +1,7 @@
use serde::{Deserialize, Serialize};
+use shoji::types::Capabilities;
-use crate::chat::{
- encoding::{Error, hanashi::Config as HanashiConfig, harmony::Config as HarmonyConfig},
- types::Capabilities,
-};
+use crate::chat::{Error, hanashi::Config as HanashiConfig, harmony::Config as HarmonyConfig};
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
#[serde(tag = "type", rename_all = "snake_case")]
diff --git a/crates/hanashi/src/chat/encoding/context.rs b/crates/hanashi/src/chat/context.rs
similarity index 100%
rename from crates/hanashi/src/chat/encoding/context.rs
rename to crates/hanashi/src/chat/context.rs
diff --git a/crates/hanashi/src/chat/encoding/harmony/bridging/tool_namespace.rs b/crates/hanashi/src/chat/encoding/harmony/bridging/tool_namespace.rs
deleted file mode 100644
index b1249d4bd..000000000
--- a/crates/hanashi/src/chat/encoding/harmony/bridging/tool_namespace.rs
+++ /dev/null
@@ -1,64 +0,0 @@
-use openai_harmony::chat::{
- ToolDescription as ExternalToolDescription, ToolNamespaceConfig as ExternalToolNamespaceConfig,
-};
-
-use crate::chat::{
- encoding::harmony::bridging::Error,
- types::{ToolDescription, ToolFunction, ToolNamespace, Value},
-};
-
-impl TryFrom<ToolNamespace> for ExternalToolNamespaceConfig {
- type Error = Error;
-
- fn try_from(namespace: ToolNamespace) -> Result<ExternalToolNamespaceConfig, Error> {
- let tools =
- namespace.tools.into_iter().map(ExternalToolDescription::try_from).collect::<Result<Vec<_>, _>>()?;
-
- Ok(ExternalToolNamespaceConfig::new(namespace.name, namespace.description, tools))
- }
-}
-
-impl TryFrom<ToolDescription> for ExternalToolDescription {
- type Error = Error;
-
- fn try_from(tool: ToolDescription) -> Result<ExternalToolDescription, Error> {
- match tool {
- ToolDescription::Function {
- function,
- } => {
- let parameters = function.parameters.map(serde_json::Value::try_from).transpose().map_err(|error| {
- Error::SerializationFailed {
- message: error.to_string(),
- }
- })?;
-
- Ok(ExternalToolDescription::new(function.name, function.description, parameters))
- },
- }
- }
-}
-
-impl From<ExternalToolNamespaceConfig> for ToolNamespace {
- fn from(namespace: ExternalToolNamespaceConfig) -> ToolNamespace {
- let tools = namespace.tools.into_iter().map(ToolDescription::from).collect();
-
- ToolNamespace {
- name: namespace.name,
- description: namespace.description,
- tools,
- }
- }
-}
-
-impl From<ExternalToolDescription> for ToolDescription {
- fn from(tool: ExternalToolDescription) -> ToolDescription {
- ToolDescription::Function {
- function: ToolFunction {
- name: tool.name,
- description: tool.description,
- parameters: tool.parameters.map(Value::from),
- r#return: None,
- },
- }
- }
-}
diff --git a/crates/hanashi/src/chat/encoding/mod.rs b/crates/hanashi/src/chat/encoding/mod.rs
deleted file mode 100644
index acd811332..000000000
--- a/crates/hanashi/src/chat/encoding/mod.rs
+++ /dev/null
@@ -1,80 +0,0 @@
-mod config;
-mod context;
-mod error;
-pub mod hanashi;
-pub mod harmony;
-mod state;
-
-pub use config::Config;
-pub use context::{Context, TokenizerLocation};
-pub use error::Error;
-pub use state::{State, SynchronizationError, SynchronizationResult};
-
-use crate::{
- Encoding as EncodingTrait,
- chat::{
- encoding::{hanashi::Encoding as HanashiEncoding, harmony::Encoding as HarmonyEncoding},
- types::{Message, TokenId},
- },
-};
-
-macro_rules! dispatch {
- ($self:expr, $method:ident $(, $arg:expr)*) => {
- match $self {
- Encoding::Hanashi(inner) => inner.$method($($arg),*).map_err(Into::into),
- Encoding::Harmony(inner) => inner.$method($($arg),*).map_err(Into::into),
- }
- };
- (infallible $self:expr, $method:ident $(, $arg:expr)*) => {
- match $self {
- Encoding::Hanashi(inner) => inner.$method($($arg),*),
- Encoding::Harmony(inner) => inner.$method($($arg),*),
- }
- };
-}
-
-pub enum Encoding {
- Hanashi(HanashiEncoding),
- Harmony(HarmonyEncoding),
-}
-
-impl EncodingTrait for Encoding {
- type Config = Config;
- type Context = Context;
- type Input = Vec<Message>;
- type Output = Vec<TokenId>;
- type State = State;
- type Error = Error;
-
- fn new(
- config: Self::Config,
- context: Self::Context,
- ) -> Result<Self, Self::Error> {
- match config {
- Config::Hanashi(config) => Ok(Encoding::Hanashi(HanashiEncoding::new(config, context)?)),
- Config::Harmony(config) => Ok(Encoding::Harmony(HarmonyEncoding::new(config, context)?)),
- }
- }
-
- fn state(&self) -> &Self::State {
- dispatch!(infallible self, state)
- }
-
- fn reset(&mut self) -> Result<(), Self::Error> {
- dispatch!(self, reset)
- }
-
- fn encode(
- &mut self,
- value: Self::Input,
- ) -> Result<(), Self::Error> {
- dispatch!(self, encode, value)
- }
-
- fn decode(
- &mut self,
- value: Self::Output,
- ) -> Result<(), Self::Error> {
- dispatch!(self, decode, value)
- }
-}
diff --git a/crates/hanashi/src/chat/encoding/error.rs b/crates/hanashi/src/chat/error.rs
similarity index 67%
rename from crates/hanashi/src/chat/encoding/error.rs
rename to crates/hanashi/src/chat/error.rs
index 735afaddf..cc4973b85 100644
--- a/crates/hanashi/src/chat/encoding/error.rs
+++ b/crates/hanashi/src/chat/error.rs
@@ -1,4 +1,4 @@
-use crate::chat::encoding::{hanashi::Error as HanashiError, harmony::Error as HarmonyError};
+use crate::chat::{hanashi::Error as HanashiError, harmony::Error as HarmonyError};
#[derive(Debug, thiserror::Error)]
#[non_exhaustive]
diff --git a/crates/hanashi/src/chat/encoding/hanashi/config/bundled.rs b/crates/hanashi/src/chat/hanashi/config/bundled.rs
similarity index 100%
rename from crates/hanashi/src/chat/encoding/hanashi/config/bundled.rs
rename to crates/hanashi/src/chat/hanashi/config/bundled.rs
diff --git a/crates/hanashi/src/chat/encoding/hanashi/config/mod.rs b/crates/hanashi/src/chat/hanashi/config/mod.rs
similarity index 96%
rename from crates/hanashi/src/chat/encoding/hanashi/config/mod.rs
rename to crates/hanashi/src/chat/hanashi/config/mod.rs
index 9a7b003dd..7b5ab509e 100644
--- a/crates/hanashi/src/chat/encoding/hanashi/config/mod.rs
+++ b/crates/hanashi/src/chat/hanashi/config/mod.rs
@@ -2,14 +2,12 @@ mod bundled;
mod tokens;
use serde::{Deserialize, Serialize};
+use shoji::types::{Capabilities, ContentBlockType, ReasoningEffort};
use token_stream_parser::token_stream::TokenStreamParserConfig;
pub use tokens::TokensConfig;
-use crate::chat::{
- encoding::hanashi::{
- error::Error, messages::rendered::FieldConfig, ordering::Config as OrderingConfig, renderer::RendererConfig,
- },
- types::{Capabilities, ContentBlockType, ReasoningEffort},
+use crate::chat::hanashi::{
+ error::Error, messages::rendered::FieldConfig, ordering::Config as OrderingConfig, renderer::RendererConfig,
};
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
diff --git a/crates/hanashi/src/chat/encoding/hanashi/config/tokens.rs b/crates/hanashi/src/chat/hanashi/config/tokens.rs
similarity index 89%
rename from crates/hanashi/src/chat/encoding/hanashi/config/tokens.rs
rename to crates/hanashi/src/chat/hanashi/config/tokens.rs
index 31cf81efd..6ad3d76bf 100644
--- a/crates/hanashi/src/chat/encoding/hanashi/config/tokens.rs
+++ b/crates/hanashi/src/chat/hanashi/config/tokens.rs
@@ -1,6 +1,5 @@
use serde::{Deserialize, Serialize};
-
-use crate::chat::types::TokenId;
+use shoji::types::TokenId;
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
pub struct TokensConfig {
diff --git a/crates/hanashi/src/chat/encoding/hanashi/error.rs b/crates/hanashi/src/chat/hanashi/error.rs
similarity index 97%
rename from crates/hanashi/src/chat/encoding/hanashi/error.rs
rename to crates/hanashi/src/chat/hanashi/error.rs
index 8544ce49b..a5277a47c 100644
--- a/crates/hanashi/src/chat/encoding/hanashi/error.rs
+++ b/crates/hanashi/src/chat/hanashi/error.rs
@@ -1,6 +1,6 @@
use token_stream_parser::token_stream::TokenStreamParserError;
-use crate::chat::encoding::{
+use crate::chat::{
SynchronizationError,
hanashi::{messages::Error as MessageError, ordering::Error as OrderingError, renderer::Error as RendererError},
};
diff --git a/crates/hanashi/src/chat/encoding/hanashi/messages/canonical/config.rs b/crates/hanashi/src/chat/hanashi/messages/canonical/config.rs
similarity index 100%
rename from crates/hanashi/src/chat/encoding/hanashi/messages/canonical/config.rs
rename to crates/hanashi/src/chat/hanashi/messages/canonical/config.rs
diff --git a/crates/hanashi/src/chat/encoding/hanashi/messages/canonical/content_block.rs b/crates/hanashi/src/chat/hanashi/messages/canonical/content_block.rs
similarity index 71%
rename from crates/hanashi/src/chat/encoding/hanashi/messages/canonical/content_block.rs
rename to crates/hanashi/src/chat/hanashi/messages/canonical/content_block.rs
index 101f6ed37..8225db393 100644
--- a/crates/hanashi/src/chat/encoding/hanashi/messages/canonical/content_block.rs
+++ b/crates/hanashi/src/chat/hanashi/messages/canonical/content_block.rs
@@ -1,6 +1,5 @@
use serde_json::Value;
-
-use crate::chat::types::ContentBlockType;
+use shoji::types::ContentBlockType;
pub struct ContentBlock {
pub r#type: ContentBlockType,
diff --git a/crates/hanashi/src/chat/encoding/hanashi/messages/canonical/message.rs b/crates/hanashi/src/chat/hanashi/messages/canonical/message.rs
similarity index 96%
rename from crates/hanashi/src/chat/encoding/hanashi/messages/canonical/message.rs
rename to crates/hanashi/src/chat/hanashi/messages/canonical/message.rs
index 1f38079f2..5a6ba48df 100644
--- a/crates/hanashi/src/chat/encoding/hanashi/messages/canonical/message.rs
+++ b/crates/hanashi/src/chat/hanashi/messages/canonical/message.rs
@@ -2,15 +2,13 @@ use std::collections::HashMap;
use indexmap::IndexMap;
use serde_json::Value;
+use shoji::types::{
+ ContentBlock as OriginalContentBlock, ContentBlockType, Message as OriginalMessage, Role, TranslationInput,
+};
-use crate::chat::{
- encoding::hanashi::messages::{
- Error,
- canonical::{Config, ContentBlock},
- },
- types::{
- ContentBlock as OriginalContentBlock, ContentBlockType, Message as OriginalMessage, Role, TranslationInput,
- },
+use crate::chat::hanashi::messages::{
+ Error,
+ canonical::{Config, ContentBlock},
};
pub struct Message {
diff --git a/crates/hanashi/src/chat/encoding/hanashi/messages/canonical/mod.rs b/crates/hanashi/src/chat/hanashi/messages/canonical/mod.rs
similarity index 100%
rename from crates/hanashi/src/chat/encoding/hanashi/messages/canonical/mod.rs
rename to crates/hanashi/src/chat/hanashi/messages/canonical/mod.rs
diff --git a/crates/hanashi/src/chat/encoding/hanashi/messages/error.rs b/crates/hanashi/src/chat/hanashi/messages/error.rs
similarity index 96%
rename from crates/hanashi/src/chat/encoding/hanashi/messages/error.rs
rename to crates/hanashi/src/chat/hanashi/messages/error.rs
index d6d74e992..c18f69f40 100644
--- a/crates/hanashi/src/chat/encoding/hanashi/messages/error.rs
+++ b/crates/hanashi/src/chat/hanashi/messages/error.rs
@@ -1,4 +1,4 @@
-use crate::chat::types::{ContentBlockType, Role};
+use shoji::types::{ContentBlockType, Role};
#[derive(Debug, thiserror::Error)]
#[non_exhaustive]
diff --git a/crates/hanashi/src/chat/encoding/hanashi/messages/mod.rs b/crates/hanashi/src/chat/hanashi/messages/mod.rs
similarity index 100%
rename from crates/hanashi/src/chat/encoding/hanashi/messages/mod.rs
rename to crates/hanashi/src/chat/hanashi/messages/mod.rs
diff --git a/crates/hanashi/src/chat/encoding/hanashi/messages/rendered/config.rs b/crates/hanashi/src/chat/hanashi/messages/rendered/config.rs
similarity index 96%
rename from crates/hanashi/src/chat/encoding/hanashi/messages/rendered/config.rs
rename to crates/hanashi/src/chat/hanashi/messages/rendered/config.rs
index 546a8609f..5e7b1b148 100644
--- a/crates/hanashi/src/chat/encoding/hanashi/messages/rendered/config.rs
+++ b/crates/hanashi/src/chat/hanashi/messages/rendered/config.rs
@@ -1,8 +1,7 @@
use indexmap::IndexMap;
use serde::{Deserialize, Serialize};
use serde_json::Value;
-
-use crate::chat::types::ContentBlockType;
+use shoji::types::ContentBlockType;
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
pub struct Field {
diff --git a/crates/hanashi/src/chat/encoding/hanashi/messages/rendered/message.rs b/crates/hanashi/src/chat/hanashi/messages/rendered/message.rs
similarity index 96%
rename from crates/hanashi/src/chat/encoding/hanashi/messages/rendered/message.rs
rename to crates/hanashi/src/chat/hanashi/messages/rendered/message.rs
index 5b0c44f2b..bb9312144 100644
--- a/crates/hanashi/src/chat/encoding/hanashi/messages/rendered/message.rs
+++ b/crates/hanashi/src/chat/hanashi/messages/rendered/message.rs
@@ -2,14 +2,12 @@ use std::collections::HashMap;
use indexmap::IndexMap;
use serde_json::{Map, Value};
+use shoji::types::{ContentBlockType, Message as OriginalMessage, Role};
-use crate::chat::{
- encoding::hanashi::messages::{
- Error,
- canonical::{Config as CanonicalConfig, Message as CanonicalMessage},
- rendered::{Config, Field, FieldConfig},
- },
- types::{ContentBlockType, Message as OriginalMessage, Role},
+use crate::chat::hanashi::messages::{
+ Error,
+ canonical::{Config as CanonicalConfig, Message as CanonicalMessage},
+ rendered::{Config, Field, FieldConfig},
};
pub struct Message {
diff --git a/crates/hanashi/src/chat/encoding/hanashi/messages/rendered/mod.rs b/crates/hanashi/src/chat/hanashi/messages/rendered/mod.rs
similarity index 100%
rename from crates/hanashi/src/chat/encoding/hanashi/messages/rendered/mod.rs
rename to crates/hanashi/src/chat/hanashi/messages/rendered/mod.rs
diff --git a/crates/hanashi/src/chat/encoding/hanashi/messages/streamed/content.rs b/crates/hanashi/src/chat/hanashi/messages/streamed/content.rs
similarity index 96%
rename from crates/hanashi/src/chat/encoding/hanashi/messages/streamed/content.rs
rename to crates/hanashi/src/chat/hanashi/messages/streamed/content.rs
index 0b7b5fb8a..153da9c78 100644
--- a/crates/hanashi/src/chat/encoding/hanashi/messages/streamed/content.rs
+++ b/crates/hanashi/src/chat/hanashi/messages/streamed/content.rs
@@ -1,10 +1,8 @@
use serde::{Deserialize, Serialize};
use serde_json::Value;
+use shoji::types::{ContentBlock, Role, ToolCall};
-use crate::chat::{
- encoding::hanashi::messages::streamed::Section,
- types::{ContentBlock, Role, ToolCall},
-};
+use crate::chat::hanashi::messages::streamed::Section;
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
#[serde(untagged)]
diff --git a/crates/hanashi/src/chat/encoding/hanashi/messages/streamed/mod.rs b/crates/hanashi/src/chat/hanashi/messages/streamed/mod.rs
similarity index 93%
rename from crates/hanashi/src/chat/encoding/hanashi/messages/streamed/mod.rs
rename to crates/hanashi/src/chat/hanashi/messages/streamed/mod.rs
index 670525177..28ae48533 100644
--- a/crates/hanashi/src/chat/encoding/hanashi/messages/streamed/mod.rs
+++ b/crates/hanashi/src/chat/hanashi/messages/streamed/mod.rs
@@ -6,8 +6,7 @@ use std::{collections::HashMap, str::FromStr};
pub use content::Content;
pub use section::Section;
use serde::{Deserialize, Deserializer};
-
-use crate::chat::types::{Message as CommonMessage, Role};
+use shoji::types::{Message as CommonMessage, Role};
#[derive(Deserialize)]
pub struct Message {
diff --git a/crates/hanashi/src/chat/encoding/hanashi/messages/streamed/section.rs b/crates/hanashi/src/chat/hanashi/messages/streamed/section.rs
similarity index 100%
rename from crates/hanashi/src/chat/encoding/hanashi/messages/streamed/section.rs
rename to crates/hanashi/src/chat/hanashi/messages/streamed/section.rs
diff --git a/crates/hanashi/src/chat/encoding/hanashi/mod.rs b/crates/hanashi/src/chat/hanashi/mod.rs
similarity index 94%
rename from crates/hanashi/src/chat/encoding/hanashi/mod.rs
rename to crates/hanashi/src/chat/hanashi/mod.rs
index 1c6ea99db..488ab0eff 100644
--- a/crates/hanashi/src/chat/encoding/hanashi/mod.rs
+++ b/crates/hanashi/src/chat/hanashi/mod.rs
@@ -3,23 +3,22 @@ mod error;
pub mod messages;
mod ordering;
pub mod renderer;
+mod token;
use std::path::PathBuf;
pub use config::Config;
pub use error::Error;
-use token_stream_parser::{Parser as _, token_stream::TokenStreamParser, types::Token as ParserToken};
+use shoji::types::{ContentBlock, Message, Token, TokenId};
+use token_stream_parser::{Parser as _, token_stream::TokenStreamParser};
use tokenizers::{Tokenizer, step_decode_stream};
use self::{config::ResolvedConfig, messages::streamed::Message as StreamedMessage, ordering::Validator};
use crate::{
Encoding as EncodingTrait,
chat::{
- encoding::{
- Context, State, SynchronizationError, SynchronizationResult, TokenizerLocation,
- hanashi::{messages::rendered::FieldConfig, renderer::Renderer},
- },
- types::{ContentBlock, Message, Token, TokenId},
+ Context, State, SynchronizationError, SynchronizationResult, TokenizerLocation,
+ hanashi::{messages::rendered::FieldConfig, renderer::Renderer, token::ToParserToken},
},
};
@@ -110,7 +109,7 @@ impl EncodingTrait for Encoding {
let text_encoding = self.tokenizer.encode(text, false).map_err(|_| Error::UnableToEncodeText)?;
for token_id in text_encoding.get_ids() {
let token = self.resolve_token(*token_id, true)?;
- self.parser.push(&ParserToken::from(token.clone()))?;
+ self.parser.push(&token.clone().to_parser_token())?;
self.state.tokens.push(token);
}
@@ -124,7 +123,7 @@ impl EncodingTrait for Encoding {
) -> Result<(), Self::Error> {
for token_id in &token_ids {
let token = self.resolve_token(*token_id, true)?;
- self.parser.push(&ParserToken::from(token.clone()))?;
+ self.parser.push(&token.clone().to_parser_token())?;
self.state.tokens.push(token);
}
diff --git a/crates/hanashi/src/chat/encoding/hanashi/ordering/config.rs b/crates/hanashi/src/chat/hanashi/ordering/config.rs
similarity index 95%
rename from crates/hanashi/src/chat/encoding/hanashi/ordering/config.rs
rename to crates/hanashi/src/chat/hanashi/ordering/config.rs
index e6d58a0c1..379658e5c 100644
--- a/crates/hanashi/src/chat/encoding/hanashi/ordering/config.rs
+++ b/crates/hanashi/src/chat/hanashi/ordering/config.rs
@@ -1,7 +1,6 @@
use indexmap::IndexMap;
use serde::{Deserialize, Serialize};
-
-use crate::chat::types::Role;
+use shoji::types::Role;
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
pub struct Config {
diff --git a/crates/hanashi/src/chat/encoding/hanashi/ordering/error.rs b/crates/hanashi/src/chat/hanashi/ordering/error.rs
similarity index 94%
rename from crates/hanashi/src/chat/encoding/hanashi/ordering/error.rs
rename to crates/hanashi/src/chat/hanashi/ordering/error.rs
index e8280b9c3..3cf8e2ffa 100644
--- a/crates/hanashi/src/chat/encoding/hanashi/ordering/error.rs
+++ b/crates/hanashi/src/chat/hanashi/ordering/error.rs
@@ -1,4 +1,4 @@
-use crate::chat::types::Role;
+use shoji::types::Role;
#[derive(Debug, thiserror::Error)]
pub enum Error {
diff --git a/crates/hanashi/src/chat/encoding/hanashi/ordering/mod.rs b/crates/hanashi/src/chat/hanashi/ordering/mod.rs
similarity index 100%
rename from crates/hanashi/src/chat/encoding/hanashi/ordering/mod.rs
rename to crates/hanashi/src/chat/hanashi/ordering/mod.rs
diff --git a/crates/hanashi/src/chat/encoding/hanashi/ordering/validator.rs b/crates/hanashi/src/chat/hanashi/ordering/validator.rs
similarity index 94%
rename from crates/hanashi/src/chat/encoding/hanashi/ordering/validator.rs
rename to crates/hanashi/src/chat/hanashi/ordering/validator.rs
index 993ae8505..729012385 100644
--- a/crates/hanashi/src/chat/encoding/hanashi/ordering/validator.rs
+++ b/crates/hanashi/src/chat/hanashi/ordering/validator.rs
@@ -1,7 +1,6 @@
-use crate::chat::{
- encoding::hanashi::ordering::{Config, Error},
- types::Role,
-};
+use shoji::types::Role;
+
+use crate::chat::hanashi::ordering::{Config, Error};
pub struct Validator {
current: Option<Role>,
diff --git a/crates/hanashi/src/chat/encoding/hanashi/renderer/config/jinja.rs b/crates/hanashi/src/chat/hanashi/renderer/config/jinja.rs
similarity index 87%
rename from crates/hanashi/src/chat/encoding/hanashi/renderer/config/jinja.rs
rename to crates/hanashi/src/chat/hanashi/renderer/config/jinja.rs
index 9157e5356..3ea0f4621 100644
--- a/crates/hanashi/src/chat/encoding/hanashi/renderer/config/jinja.rs
+++ b/crates/hanashi/src/chat/hanashi/renderer/config/jinja.rs
@@ -1,6 +1,6 @@
use serde::{Deserialize, Serialize};
-use crate::chat::encoding::hanashi::renderer::config::JinjaFunction;
+use crate::chat::hanashi::renderer::config::JinjaFunction;
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
pub struct JinjaConfig {
diff --git a/crates/hanashi/src/chat/encoding/hanashi/renderer/config/jinja_function.rs b/crates/hanashi/src/chat/hanashi/renderer/config/jinja_function.rs
similarity index 100%
rename from crates/hanashi/src/chat/encoding/hanashi/renderer/config/jinja_function.rs
rename to crates/hanashi/src/chat/hanashi/renderer/config/jinja_function.rs
diff --git a/crates/hanashi/src/chat/encoding/hanashi/renderer/config/mod.rs b/crates/hanashi/src/chat/hanashi/renderer/config/mod.rs
similarity index 89%
rename from crates/hanashi/src/chat/encoding/hanashi/renderer/config/mod.rs
rename to crates/hanashi/src/chat/hanashi/renderer/config/mod.rs
index ede58dee2..32396622d 100644
--- a/crates/hanashi/src/chat/encoding/hanashi/renderer/config/mod.rs
+++ b/crates/hanashi/src/chat/hanashi/renderer/config/mod.rs
@@ -5,13 +5,11 @@ use indexmap::IndexMap;
pub use jinja::JinjaConfig;
pub use jinja_function::JinjaFunction;
use serde::{Deserialize, Serialize};
+use shoji::types::{ContentBlockType, Role};
-use crate::chat::{
- encoding::hanashi::messages::{
- canonical::Config as CanonicalConfig,
- rendered::{Config as RenderedConfig, Field, FieldConfig},
- },
- types::{ContentBlockType, Role},
+use crate::chat::hanashi::messages::{
+ canonical::Config as CanonicalConfig,
+ rendered::{Config as RenderedConfig, Field, FieldConfig},
};
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
diff --git a/crates/hanashi/src/chat/encoding/hanashi/renderer/error.rs b/crates/hanashi/src/chat/hanashi/renderer/error.rs
similarity index 87%
rename from crates/hanashi/src/chat/encoding/hanashi/renderer/error.rs
rename to crates/hanashi/src/chat/hanashi/renderer/error.rs
index 5e6c7a262..2068ac936 100644
--- a/crates/hanashi/src/chat/encoding/hanashi/renderer/error.rs
+++ b/crates/hanashi/src/chat/hanashi/renderer/error.rs
@@ -1,4 +1,4 @@
-use crate::chat::encoding::hanashi::messages::Error as MessageError;
+use crate::chat::hanashi::messages::Error as MessageError;
#[derive(Debug, thiserror::Error)]
#[non_exhaustive]
diff --git a/crates/hanashi/src/chat/encoding/hanashi/renderer/functions/mod.rs b/crates/hanashi/src/chat/hanashi/renderer/functions/mod.rs
similarity index 100%
rename from crates/hanashi/src/chat/encoding/hanashi/renderer/functions/mod.rs
rename to crates/hanashi/src/chat/hanashi/renderer/functions/mod.rs
diff --git a/crates/hanashi/src/chat/encoding/hanashi/renderer/functions/raise_exception.rs b/crates/hanashi/src/chat/hanashi/renderer/functions/raise_exception.rs
similarity index 100%
rename from crates/hanashi/src/chat/encoding/hanashi/renderer/functions/raise_exception.rs
rename to crates/hanashi/src/chat/hanashi/renderer/functions/raise_exception.rs
diff --git a/crates/hanashi/src/chat/encoding/hanashi/renderer/functions/strftime_now.rs b/crates/hanashi/src/chat/hanashi/renderer/functions/strftime_now.rs
similarity index 100%
rename from crates/hanashi/src/chat/encoding/hanashi/renderer/functions/strftime_now.rs
rename to crates/hanashi/src/chat/hanashi/renderer/functions/strftime_now.rs
diff --git a/crates/hanashi/src/chat/encoding/hanashi/renderer/functions/to_json.rs b/crates/hanashi/src/chat/hanashi/renderer/functions/to_json.rs
similarity index 100%
rename from crates/hanashi/src/chat/encoding/hanashi/renderer/functions/to_json.rs
rename to crates/hanashi/src/chat/hanashi/renderer/functions/to_json.rs
diff --git a/crates/hanashi/src/chat/encoding/hanashi/renderer/mod.rs b/crates/hanashi/src/chat/hanashi/renderer/mod.rs
similarity index 95%
rename from crates/hanashi/src/chat/encoding/hanashi/renderer/mod.rs
rename to crates/hanashi/src/chat/hanashi/renderer/mod.rs
index f0832c112..1830392fb 100644
--- a/crates/hanashi/src/chat/encoding/hanashi/renderer/mod.rs
+++ b/crates/hanashi/src/chat/hanashi/renderer/mod.rs
@@ -4,15 +4,13 @@ mod functions;
pub use config::{JinjaFunction, RendererConfig};
pub use error::Error;
+use functions::{raise_exception, strftime_now, to_json};
use indexmap::IndexMap;
use minijinja::Environment;
use minijinja_contrib::pycompat::unknown_method_callback;
+use shoji::types::{Message, Token};
-use self::functions::{raise_exception, strftime_now, to_json};
-use crate::chat::{
- encoding::hanashi::messages::rendered::Message as RenderedMessage,
- types::{Message, Token},
-};
+use crate::chat::hanashi::messages::rendered::Message as RenderedMessage;
static TEMPLATE_NAME: &str = "chat_template";
diff --git a/crates/hanashi/src/chat/hanashi/token.rs b/crates/hanashi/src/chat/hanashi/token.rs
new file mode 100644
index 000000000..2eeb93014
--- /dev/null
+++ b/crates/hanashi/src/chat/hanashi/token.rs
@@ -0,0 +1,20 @@
+use shoji::types::Token;
+use token_stream_parser::types::Token as ParserToken;
+
+pub trait ToParserToken {
+ type Output;
+
+ fn to_parser_token(self) -> Self::Output;
+}
+
+impl ToParserToken for Token {
+ type Output = ParserToken;
+
+ fn to_parser_token(self) -> Self::Output {
+ ParserToken {
+ id: self.id,
+ value: self.value,
+ is_special: self.is_special,
+ }
+ }
+}
diff --git a/crates/hanashi/src/chat/encoding/harmony/bridging/encoding_name.rs b/crates/hanashi/src/chat/harmony/bridging/encoding_name.rs
similarity index 91%
rename from crates/hanashi/src/chat/encoding/harmony/bridging/encoding_name.rs
rename to crates/hanashi/src/chat/harmony/bridging/encoding_name.rs
index 5054fc33f..fc4f59187 100644
--- a/crates/hanashi/src/chat/encoding/harmony/bridging/encoding_name.rs
+++ b/crates/hanashi/src/chat/harmony/bridging/encoding_name.rs
@@ -1,6 +1,6 @@
use openai_harmony::HarmonyEncodingName as ExternalEncodingName;
-use crate::chat::encoding::harmony::EncodingName;
+use crate::chat::harmony::EncodingName;
impl From<EncodingName> for ExternalEncodingName {
fn from(encoding: EncodingName) -> ExternalEncodingName {
diff --git a/crates/hanashi/src/chat/encoding/harmony/bridging/message.rs b/crates/hanashi/src/chat/harmony/bridging/message.rs
similarity index 97%
rename from crates/hanashi/src/chat/encoding/harmony/bridging/message.rs
rename to crates/hanashi/src/chat/harmony/bridging/message.rs
index cdce27bf5..b25deafc9 100644
--- a/crates/hanashi/src/chat/encoding/harmony/bridging/message.rs
+++ b/crates/hanashi/src/chat/harmony/bridging/message.rs
@@ -2,14 +2,11 @@ use std::collections::HashMap;
use openai_harmony::chat::{
Author as ExternalAuthor, Content as ExternalContent, DeveloperContent as ExternalDeveloperContent,
- Message as ExternalMessage, ReasoningEffort as ExternalReasoningEffort, Role as ExternalRole,
- SystemContent as ExternalSystemContent, TextContent, ToolNamespaceConfig as ExternalToolNamespaceConfig,
+ Message as ExternalMessage, Role as ExternalRole, SystemContent as ExternalSystemContent, TextContent,
};
+use shoji::types::{ContentBlock, Message, ReasoningEffort, Role, ToolCall, ToolNamespace, Value};
-use crate::chat::{
- encoding::harmony::bridging::Error,
- types::{ContentBlock, Message, ReasoningEffort, Role, ToolCall, ToolNamespace, Value},
-};
+use crate::chat::harmony::bridging::{Error, FromHarmony, ToHarmony};
const FUNCTIONS_NAMESPACE: &str = "functions";
const CHANNEL_ANALYSIS: &str = "analysis";
@@ -42,7 +39,7 @@ pub fn bridge_messages_to_harmony(messages: &[Message]) -> Result<Vec<ExternalMe
value,
} => {
system_filled = true;
- system_content.reasoning_effort = Some(ExternalReasoningEffort::try_from(value.clone())?);
+ system_content.reasoning_effort = Some(value.clone().to_harmony()?);
},
ContentBlock::ConversationStartDate {
value,
@@ -124,8 +121,7 @@ pub fn bridge_messages_to_harmony(messages: &[Message]) -> Result<Vec<ExternalMe
namespaces,
} => {
for namespace in namespaces {
- developer_content = developer_content
- .with_tools(ExternalToolNamespaceConfig::try_from(namespace.clone())?);
+ developer_content = developer_content.with_tools(namespace.clone().to_harmony()?);
}
},
other => {
@@ -314,7 +310,7 @@ pub fn bridge_messages_from_harmony(messages: &[ExternalMessage]) -> Result<Vec<
}
if let Some(effort) = &system_content.reasoning_effort {
content.push(ContentBlock::ReasoningEffort {
- value: ReasoningEffort::from(*effort),
+ value: ReasoningEffort::from_harmony(*effort),
});
}
if let Some(date) = &system_content.conversation_start_date {
@@ -369,7 +365,7 @@ pub fn bridge_messages_from_harmony(messages: &[ExternalMessage]) -> Result<Vec<
}
if let Some(tools) = &developer_content.tools {
let namespaces: Vec<ToolNamespace> =
- tools.values().cloned().map(ToolNamespace::from).collect();
+ tools.values().cloned().map(ToolNamespace::from_harmony).collect();
if !namespaces.is_empty() {
content.push(ContentBlock::Tools {
namespaces,
diff --git a/crates/hanashi/src/chat/encoding/harmony/bridging/mod.rs b/crates/hanashi/src/chat/harmony/bridging/mod.rs
similarity index 82%
rename from crates/hanashi/src/chat/encoding/harmony/bridging/mod.rs
rename to crates/hanashi/src/chat/harmony/bridging/mod.rs
index d2866147e..8b22da73f 100644
--- a/crates/hanashi/src/chat/encoding/harmony/bridging/mod.rs
+++ b/crates/hanashi/src/chat/harmony/bridging/mod.rs
@@ -5,8 +5,7 @@ mod role;
mod tool_namespace;
pub use message::{bridge_messages_from_harmony, bridge_messages_to_harmony};
-
-use crate::chat::types::{ContentBlockType, ReasoningEffort, Role};
+use shoji::types::{ContentBlockType, ReasoningEffort, Role};
#[derive(Debug, thiserror::Error)]
#[non_exhaustive]
@@ -43,3 +42,15 @@ pub enum Error {
message: String,
},
}
+
+pub trait ToHarmony {
+ type Output;
+
+ fn to_harmony(self) -> Result<Self::Output, Error>;
+}
+
+pub trait FromHarmony: Sized {
+ type Input;
+
+ fn from_harmony(input: Self::Input) -> Self;
+}
diff --git a/crates/hanashi/src/chat/encoding/harmony/bridging/reasoning_effort.rs b/crates/hanashi/src/chat/harmony/bridging/reasoning_effort.rs
similarity index 58%
rename from crates/hanashi/src/chat/encoding/harmony/bridging/reasoning_effort.rs
rename to crates/hanashi/src/chat/harmony/bridging/reasoning_effort.rs
index 905a4d573..930f7403f 100644
--- a/crates/hanashi/src/chat/encoding/harmony/bridging/reasoning_effort.rs
+++ b/crates/hanashi/src/chat/harmony/bridging/reasoning_effort.rs
@@ -1,12 +1,13 @@
use openai_harmony::chat::ReasoningEffort as ExternalReasoningEffort;
+use shoji::types::ReasoningEffort;
-use crate::chat::{encoding::harmony::bridging::Error, types::ReasoningEffort};
+use crate::chat::harmony::bridging::{Error, FromHarmony, ToHarmony};
-impl TryFrom<ReasoningEffort> for ExternalReasoningEffort {
- type Error = Error;
+impl ToHarmony for ReasoningEffort {
+ type Output = ExternalReasoningEffort;
- fn try_from(reasoning_effort: ReasoningEffort) -> Result<ExternalReasoningEffort, Error> {
- match reasoning_effort {
+ fn to_harmony(self) -> Result<Self::Output, Error> {
+ match self {
ReasoningEffort::Low => Ok(ExternalReasoningEffort::Low),
ReasoningEffort::Medium => Ok(ExternalReasoningEffort::Medium),
ReasoningEffort::High => Ok(ExternalReasoningEffort::High),
@@ -17,9 +18,11 @@ impl TryFrom<ReasoningEffort> for ExternalReasoningEffort {
}
}
-impl From<ExternalReasoningEffort> for ReasoningEffort {
- fn from(reasoning_effort: ExternalReasoningEffort) -> ReasoningEffort {
- match reasoning_effort {
+impl FromHarmony for ReasoningEffort {
+ type Input = ExternalReasoningEffort;
+
+ fn from_harmony(input: Self::Input) -> Self {
+ match input {
ExternalReasoningEffort::Low => ReasoningEffort::Low,
ExternalReasoningEffort::Medium => ReasoningEffort::Medium,
ExternalReasoningEffort::High => ReasoningEffort::High,
diff --git a/crates/hanashi/src/chat/encoding/harmony/bridging/role.rs b/crates/hanashi/src/chat/harmony/bridging/role.rs
similarity index 65%
rename from crates/hanashi/src/chat/encoding/harmony/bridging/role.rs
rename to crates/hanashi/src/chat/harmony/bridging/role.rs
index 433659832..58485e84b 100644
--- a/crates/hanashi/src/chat/encoding/harmony/bridging/role.rs
+++ b/crates/hanashi/src/chat/harmony/bridging/role.rs
@@ -1,12 +1,13 @@
use openai_harmony::chat::Role as ExternalRole;
+use shoji::types::Role;
-use crate::chat::{encoding::harmony::bridging::Error, types::Role};
+use crate::chat::harmony::bridging::{Error, FromHarmony, ToHarmony};
-impl TryFrom<Role> for ExternalRole {
- type Error = Error;
+impl ToHarmony for Role {
+ type Output = ExternalRole;
- fn try_from(role: Role) -> Result<ExternalRole, Error> {
- match role {
+ fn to_harmony(self) -> Result<Self::Output, Error> {
+ match self {
Role::User {} => Ok(ExternalRole::User),
Role::Assistant {} => Ok(ExternalRole::Assistant),
Role::System {} => Ok(ExternalRole::System),
@@ -15,15 +16,17 @@ impl TryFrom<Role> for ExternalRole {
Role::Custom {
..
} => Err(Error::UnsupportedRole {
- role: role.clone(),
+ role: self.clone(),
}),
}
}
}
-impl From<ExternalRole> for Role {
- fn from(role: ExternalRole) -> Role {
- match role {
+impl FromHarmony for Role {
+ type Input = ExternalRole;
+
+ fn from_harmony(input: Self::Input) -> Self {
+ match input {
ExternalRole::User => Role::User {},
ExternalRole::Assistant => Role::Assistant {},
ExternalRole::System => Role::System {},
diff --git a/crates/hanashi/src/chat/harmony/bridging/tool_namespace.rs b/crates/hanashi/src/chat/harmony/bridging/tool_namespace.rs
new file mode 100644
index 000000000..b983ddefa
--- /dev/null
+++ b/crates/hanashi/src/chat/harmony/bridging/tool_namespace.rs
@@ -0,0 +1,65 @@
+use openai_harmony::chat::{
+ ToolDescription as ExternalToolDescription, ToolNamespaceConfig as ExternalToolNamespaceConfig,
+};
+use shoji::types::{ToolDescription, ToolFunction, ToolNamespace, Value};
+
+use crate::chat::harmony::bridging::{Error, FromHarmony, ToHarmony};
+
+impl ToHarmony for ToolNamespace {
+ type Output = ExternalToolNamespaceConfig;
+
+ fn to_harmony(self) -> Result<Self::Output, Error> {
+ let tools = self.tools.into_iter().map(ToolDescription::to_harmony).collect::<Result<Vec<_>, _>>()?;
+
+ Ok(ExternalToolNamespaceConfig::new(self.name, self.description, tools))
+ }
+}
+
+impl FromHarmony for ToolNamespace {
+ type Input = ExternalToolNamespaceConfig;
+
+ fn from_harmony(input: Self::Input) -> Self {
+ let tools = input.tools.into_iter().map(ToolDescription::from_harmony).collect();
+
+ ToolNamespace {
+ name: input.name,
+ description: input.description,
+ tools,
+ }
+ }
+}
+
+impl ToHarmony for ToolDescription {
+ type Output = ExternalToolDescription;
+
+ fn to_harmony(self) -> Result<Self::Output, Error> {
+ match self {
+ ToolDescription::Function {
+ function,
+ } => {
+ let parameters = function.parameters.map(serde_json::Value::try_from).transpose().map_err(|error| {
+ Error::SerializationFailed {
+ message: error.to_string(),
+ }
+ })?;
+
+ Ok(ExternalToolDescription::new(function.name, function.description, parameters))
+ },
+ }
+ }
+}
+
+impl FromHarmony for ToolDescription {
+ type Input = ExternalToolDescription;
+
+ fn from_harmony(input: Self::Input) -> Self {
+ ToolDescription::Function {
+ function: ToolFunction {
+ name: input.name,
+ description: input.description,
+ parameters: input.parameters.map(Value::from),
+ r#return: None,
+ },
+ }
+ }
+}
diff --git a/crates/hanashi/src/chat/encoding/harmony/config.rs b/crates/hanashi/src/chat/harmony/config.rs
similarity index 89%
rename from crates/hanashi/src/chat/encoding/harmony/config.rs
rename to crates/hanashi/src/chat/harmony/config.rs
index 1d446d26b..314dba09d 100644
--- a/crates/hanashi/src/chat/encoding/harmony/config.rs
+++ b/crates/hanashi/src/chat/harmony/config.rs
@@ -1,6 +1,7 @@
use serde::{Deserialize, Serialize};
+use shoji::types::Capabilities;
-use crate::chat::{encoding::harmony::EncodingName, types::Capabilities};
+use crate::chat::harmony::EncodingName;
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
pub struct Config {
diff --git a/crates/hanashi/src/chat/encoding/harmony/encoding_name.rs b/crates/hanashi/src/chat/harmony/encoding_name.rs
similarity index 100%
rename from crates/hanashi/src/chat/encoding/harmony/encoding_name.rs
rename to crates/hanashi/src/chat/harmony/encoding_name.rs
diff --git a/crates/hanashi/src/chat/encoding/harmony/error.rs b/crates/hanashi/src/chat/harmony/error.rs
similarity index 86%
rename from crates/hanashi/src/chat/encoding/harmony/error.rs
rename to crates/hanashi/src/chat/harmony/error.rs
index e058d499d..0e9830770 100644
--- a/crates/hanashi/src/chat/encoding/harmony/error.rs
+++ b/crates/hanashi/src/chat/harmony/error.rs
@@ -1,4 +1,5 @@
-use crate::chat::encoding::{SynchronizationError, harmony::bridging::Error as BridgingError};
+use crate::chat::{SynchronizationError, harmony::bridging::Error as BridgingError};
+
#[derive(Debug, thiserror::Error)]
#[non_exhaustive]
pub enum Error {
diff --git a/crates/hanashi/src/chat/encoding/harmony/mod.rs b/crates/hanashi/src/chat/harmony/mod.rs
similarity index 97%
rename from crates/hanashi/src/chat/encoding/harmony/mod.rs
rename to crates/hanashi/src/chat/harmony/mod.rs
index 23da74d02..1661a4080 100644
--- a/crates/hanashi/src/chat/encoding/harmony/mod.rs
+++ b/crates/hanashi/src/chat/harmony/mod.rs
@@ -15,13 +15,11 @@ use openai_harmony::{
},
load_harmony_encoding,
};
+use shoji::types::{Message, Token, TokenId};
use crate::{
Encoding as EncodingTrait,
- chat::{
- encoding::{Context, State, TokenizerLocation},
- types::{Message, Token, TokenId},
- },
+ chat::{Context, State, TokenizerLocation},
};
pub struct Encoding {
diff --git a/crates/hanashi/src/chat/mod.rs b/crates/hanashi/src/chat/mod.rs
index 14b51ac33..39dad86df 100644
--- a/crates/hanashi/src/chat/mod.rs
+++ b/crates/hanashi/src/chat/mod.rs
@@ -1,4 +1,78 @@
-pub mod encoding;
-pub mod types;
+mod config;
+mod context;
+mod error;
+pub mod hanashi;
+pub mod harmony;
+mod state;
-pub use encoding::{Config, Context, Encoding, Error, State};
+pub use config::Config;
+pub use context::{Context, TokenizerLocation};
+pub use error::Error;
+use shoji::types::{Message, TokenId};
+pub use state::{State, SynchronizationError, SynchronizationResult};
+
+use crate::{
+ Encoding as EncodingTrait,
+ chat::{hanashi::Encoding as HanashiEncoding, harmony::Encoding as HarmonyEncoding},
+};
+
+macro_rules! dispatch {
+ ($self:expr, $method:ident $(, $arg:expr)*) => {
+ match $self {
+ Encoding::Hanashi(inner) => inner.$method($($arg),*).map_err(Into::into),
+ Encoding::Harmony(inner) => inner.$method($($arg),*).map_err(Into::into),
+ }
+ };
+ (infallible $self:expr, $method:ident $(, $arg:expr)*) => {
+ match $self {
+ Encoding::Hanashi(inner) => inner.$method($($arg),*),
+ Encoding::Harmony(inner) => inner.$method($($arg),*),
+ }
+ };
+}
+
+pub enum Encoding {
+ Hanashi(HanashiEncoding),
+ Harmony(HarmonyEncoding),
+}
+
+impl EncodingTrait for Encoding {
+ type Config = Config;
+ type Context = Context;
+ type Input = Vec<Message>;
+ type Output = Vec<TokenId>;
+ type State = State;
+ type Error = Error;
+
+ fn new(
+ config: Self::Config,
+ context: Self::Context,
+ ) -> Result<Self, Self::Error> {
+ match config {
+ Config::Hanashi(config) => Ok(Encoding::Hanashi(HanashiEncoding::new(config, context)?)),
+ Config::Harmony(config) => Ok(Encoding::Harmony(HarmonyEncoding::new(config, context)?)),
+ }
+ }
+
+ fn state(&self) -> &Self::State {
+ dispatch!(infallible self, state)
+ }
+
+ fn reset(&mut self) -> Result<(), Self::Error> {
+ dispatch!(self, reset)
+ }
+
+ fn encode(
+ &mut self,
+ value: Self::Input,
+ ) -> Result<(), Self::Error> {
+ dispatch!(self, encode, value)
+ }
+
+ fn decode(
+ &mut self,
+ value: Self::Output,
+ ) -> Result<(), Self::Error> {
+ dispatch!(self, decode, value)
+ }
+}
diff --git a/crates/hanashi/src/chat/encoding/state.rs b/crates/hanashi/src/chat/state.rs
similarity index 97%
rename from crates/hanashi/src/chat/encoding/state.rs
rename to crates/hanashi/src/chat/state.rs
index d621a21e4..8d3e1f7e9 100644
--- a/crates/hanashi/src/chat/encoding/state.rs
+++ b/crates/hanashi/src/chat/state.rs
@@ -1,6 +1,5 @@
use serde::{Deserialize, Serialize};
-
-use crate::chat::types::{Message, Token};
+use shoji::types::{Message, Token};
#[derive(Debug, thiserror::Error)]
#[non_exhaustive]
diff --git a/crates/hanashi/src/lib.rs b/crates/hanashi/src/lib.rs
index 7bd21c99c..f5ed42200 100644
--- a/crates/hanashi/src/lib.rs
+++ b/crates/hanashi/src/lib.rs
@@ -1,6 +1,3 @@
-#[cfg(feature = "bindings-uniffi")]
-uniffi::setup_scaffolding!();
-
pub mod chat;
pub trait Encoding {
diff --git a/crates/hanashi/tests/helpers/mod.rs b/crates/hanashi/tests/helpers/mod.rs
index e30fa8cf2..f374d7870 100644
--- a/crates/hanashi/tests/helpers/mod.rs
+++ b/crates/hanashi/tests/helpers/mod.rs
@@ -2,10 +2,8 @@
use std::{collections::HashMap, path::PathBuf};
-use hanashi::chat::types::{
- ContentBlock, Message, ReasoningEffort, Role, ToolDescription, ToolNamespace, TranslationInput,
-};
use serde::Deserialize;
+use shoji::types::{ContentBlock, Message, ReasoningEffort, Role, ToolDescription, ToolNamespace, TranslationInput};
use tokenizers::Tokenizer;
fn test_data_path() -> PathBuf {
diff --git a/crates/hanashi/tests/test_encoding.rs b/crates/hanashi/tests/test_encoding.rs
index 1268a3123..f32d04702 100644
--- a/crates/hanashi/tests/test_encoding.rs
+++ b/crates/hanashi/tests/test_encoding.rs
@@ -5,18 +5,16 @@ use std::collections::HashMap;
use hanashi::{
Encoding as EncodingTrait,
chat::{
- encoding::{
- Config as EncodingConfig, Context, Encoding, TokenizerLocation,
- hanashi::Config as HanashiConfig,
- harmony::{Config as HarmonyConfig, EncodingName as HarmonyEncodingName},
- },
- types::{ContentBlock, Message, ReasoningEffort, Role},
+ Config as EncodingConfig, Context, Encoding, TokenizerLocation,
+ hanashi::Config as HanashiConfig,
+ harmony::{Config as HarmonyConfig, EncodingName as HarmonyEncodingName},
},
};
use helpers::{
build_messages, load_registry, load_response_test_data, load_tokenizer, normalize_pattern, response_path,
tokenizer_directory,
};
+use shoji::types::{ContentBlock, Message, ReasoningEffort, Role};
fn print_warning(message: &str) {
println!("\x1b[33m{}\x1b[0m", message);
diff --git a/crates/nagare/Cargo.toml b/crates/nagare/Cargo.toml
index f6b4aeccd..3b8e049a1 100644
--- a/crates/nagare/Cargo.toml
+++ b/crates/nagare/Cargo.toml
@@ -8,29 +8,10 @@ authors.workspace = true
repository.workspace = true
[dependencies]
-download-manager.workspace = true
+shoji.workspace = true
+hanashi.workspace = true
serde.workspace = true
serde_json.workspace = true
thiserror.workspace = true
-futures.workspace = true
-tokio.workspace = true
-tokio-stream.workspace = true
-dirs.workspace = true
-sysinfo.workspace = true
-reqwest.workspace = true
indexmap.workspace = true
-tracing.workspace = true
-uuid.workspace = true
-futures-util.workspace = true
-
-[target.'cfg(target_vendor = "apple")'.dependencies]
-objc2.workspace = true
-objc2-foundation.workspace = true
-objc2-security.workspace = true
-
-[dev-dependencies]
-tracing-subscriber.workspace = true
-tracing-appender.workspace = true
-chrono.workspace = true
-tempfile.workspace = true
-indicatif.workspace = true
+reqwest.workspace = true
diff --git a/crates/nagare/src/api/client.rs b/crates/nagare/src/api/client.rs
index 25bf06ffd..04286dbe5 100644
--- a/crates/nagare/src/api/client.rs
+++ b/crates/nagare/src/api/client.rs
@@ -10,7 +10,13 @@ pub struct Client {
impl Client {
pub fn new(config: Config) -> Result<Self, Error> {
- let client = reqwest::Client::builder().timeout(config.timeout).build().map_err(Error::from)?;
+ #[allow(unused_mut)]
+ let mut client_builder = reqwest::Client::builder();
+ #[cfg(not(target_family = "wasm"))]
+ {
+ client_builder = client_builder.timeout(config.timeout);
+ }
+ let client = client_builder.build().map_err(Error::from)?;
Ok(Self {
config,
@@ -51,7 +57,7 @@ impl Client {
body,
});
}
- response.json::<T>().await.map_err(|e| Error::Decode(e.to_string()))
+ response.json::<T>().await.map_err(|error| Error::Decode(error.to_string()))
}
}
diff --git a/crates/nagare/src/backend/mod.rs b/crates/nagare/src/backend/mod.rs
deleted file mode 100644
index 84027ef2e..000000000
--- a/crates/nagare/src/backend/mod.rs
+++ /dev/null
@@ -1,15 +0,0 @@
-use std::{error::Error, fmt::Debug};
-
-use serde::{Serialize, de::DeserializeOwned};
-
-pub trait Backend: Debug + Copy + 'static {
- type Error: Error;
- type Config: Serialize + DeserializeOwned;
- type BackendInstance: BackendInstance<Backend = Self>;
-}
-
-pub trait BackendInstance: Sized {
- type Backend: Backend<BackendInstance = Self>;
-
- fn new(config: <Self::Backend as Backend>::Config) -> Result<Self, <Self::Backend as Backend>::Error>;
-}
diff --git a/crates/nagare/src/helpers/mod.rs b/crates/nagare/src/helpers/mod.rs
deleted file mode 100644
index 029496f76..000000000
--- a/crates/nagare/src/helpers/mod.rs
+++ /dev/null
@@ -1,3 +0,0 @@
-mod shared_access;
-
-pub use shared_access::SharedAccess;
diff --git a/crates/nagare/src/lib.rs b/crates/nagare/src/lib.rs
index bc1b8539b..e5fdf85ee 100644
--- a/crates/nagare/src/lib.rs
+++ b/crates/nagare/src/lib.rs
@@ -1,6 +1 @@
pub mod api;
-pub mod backend;
-pub mod device;
-pub mod helpers;
-pub mod registry;
-pub mod storage;
diff --git a/crates/shoji/Cargo.toml b/crates/shoji/Cargo.toml
new file mode 100644
index 000000000..7be0cd8e6
--- /dev/null
+++ b/crates/shoji/Cargo.toml
@@ -0,0 +1,47 @@
+[package]
+name = "shoji"
+version.workspace = true
+edition.workspace = true
+rust-version.workspace = true
+license.workspace = true
+authors.workspace = true
+repository.workspace = true
+
+[lib]
+crate-type = ["lib", "cdylib", "staticlib"]
+
+[features]
+default = []
+bindings = [
+ "bindings-uniffi",
+ "bindings-napi",
+ "bindings-pyo3",
+ "bindings-wasm",
+]
+bindings-uniffi = ["dep:uniffi"]
+bindings-napi = ["dep:napi", "dep:napi-derive", "dep:napi-build"]
+bindings-pyo3 = ["dep:pyo3"]
+bindings-wasm = [
+ "dep:wasm-bindgen",
+ "dep:serde-wasm-bindgen",
+ "dep:wasm-bindgen-futures",
+ "dep:tsify",
+]
+
+[dependencies]
+bindings.workspace = true
+serde.workspace = true
+serde_json.workspace = true
+thiserror.workspace = true
+indexmap.workspace = true
+uniffi = { workspace = true, optional = true }
+napi = { workspace = true, optional = true }
+napi-derive = { workspace = true, optional = true }
+pyo3 = { workspace = true, optional = true }
+wasm-bindgen = { workspace = true, optional = true }
+serde-wasm-bindgen = { workspace = true, optional = true }
+wasm-bindgen-futures = { workspace = true, optional = true }
+tsify = { workspace = true, optional = true }
+
+[build-dependencies]
+napi-build = { workspace = true, optional = true }
diff --git a/crates/shoji/build.rs b/crates/shoji/build.rs
new file mode 100644
index 000000000..6de3825da
--- /dev/null
+++ b/crates/shoji/build.rs
@@ -0,0 +1,4 @@
+fn main() {
+ #[cfg(feature = "bindings-napi")]
+ napi_build::setup();
+}
diff --git a/crates/shoji/src/lib.rs b/crates/shoji/src/lib.rs
new file mode 100644
index 000000000..95edd8254
--- /dev/null
+++ b/crates/shoji/src/lib.rs
@@ -0,0 +1,5 @@
+#[cfg(feature = "bindings-uniffi")]
+uniffi::setup_scaffolding!();
+
+pub mod traits;
+pub mod types;
diff --git a/crates/shoji/src/traits/backend.rs b/crates/shoji/src/traits/backend.rs
new file mode 100644
index 000000000..c864f8a46
--- /dev/null
+++ b/crates/shoji/src/traits/backend.rs
@@ -0,0 +1,30 @@
+use std::error::Error;
+
+use serde::{Serialize, de::DeserializeOwned};
+
+pub trait BackendInstance: Send + Sync {
+ type Error: Error;
+ type Config: Serialize + DeserializeOwned;
+
+ fn identifier(&self) -> String;
+ fn version(&self) -> String;
+
+ fn new(config: Self::Config) -> Result<Self, Self::Error>
+ where
+ Self: Sized;
+}
+
+pub trait Backend: Send + Sync {
+ fn identifier(&self) -> String;
+ fn version(&self) -> String;
+}
+
+impl<B: BackendInstance> Backend for B {
+ fn identifier(&self) -> String {
+ self.identifier()
+ }
+
+ fn version(&self) -> String {
+ self.version()
+ }
+}
diff --git a/crates/shoji/src/traits/mod.rs b/crates/shoji/src/traits/mod.rs
new file mode 100644
index 000000000..bfc9cfba3
--- /dev/null
+++ b/crates/shoji/src/traits/mod.rs
@@ -0,0 +1,5 @@
+mod backend;
+mod registry;
+
+pub use backend::{Backend, BackendInstance};
+pub use registry::Registry;
diff --git a/crates/nagare/src/registry/mod.rs b/crates/shoji/src/traits/registry.rs
similarity index 63%
rename from crates/nagare/src/registry/mod.rs
rename to crates/shoji/src/traits/registry.rs
index 76b4cf976..9ba5a3192 100644
--- a/crates/nagare/src/registry/mod.rs
+++ b/crates/shoji/src/traits/registry.rs
@@ -1,27 +1,18 @@
-mod cached;
-mod error;
-mod fixed;
-mod merged;
-pub mod types;
+use std::{error::Error, future::Future, pin::Pin};
-use std::{future::Future, pin::Pin};
-
-pub use cached::CachedRegistry;
-pub use error::Error;
-pub use fixed::FixedRegistry;
-pub use merged::MergedRegistry;
-
-use crate::registry::types::Model;
+use crate::types::Model;
pub trait Registry: Send + Sync {
+ type Error: Error;
+
fn indentifier(&self) -> String;
- fn models(&self) -> Pin<Box<dyn Future<Output = Result<Vec<Model>, Error>> + Send + '_>>;
+ fn models(&self) -> Pin<Box<dyn Future<Output = Result<Vec<Model>, Self::Error>> + Send + '_>>;
fn model_by_identifier(
&self,
identifier: &str,
- ) -> Pin<Box<dyn Future<Output = Result<Option<Model>, Error>> + Send + '_>> {
+ ) -> Pin<Box<dyn Future<Output = Result<Option<Model>, Self::Error>> + Send + '_>> {
let identifier = identifier.to_string();
Box::pin(async move {
let models = self.models().await?;
@@ -33,7 +24,7 @@ pub trait Registry: Send + Sync {
fn model_by_repo_id(
&self,
repo_id: &str,
- ) -> Pin<Box<dyn Future<Output = Result<Option<Model>, Error>> + Send + '_>> {
+ ) -> Pin<Box<dyn Future<Output = Result<Option<Model>, Self::Error>> + Send + '_>> {
let repo_id = repo_id.to_string();
Box::pin(async move {
let models = self.models().await?;
diff --git a/crates/shoji/src/types/basic/mod.rs b/crates/shoji/src/types/basic/mod.rs
new file mode 100644
index 000000000..9bfa2d446
--- /dev/null
+++ b/crates/shoji/src/types/basic/mod.rs
@@ -0,0 +1,5 @@
+mod token;
+mod value;
+
+pub use token::{Token, TokenId, TokenValue};
+pub use value::Value;
diff --git a/crates/hanashi/src/chat/types/token.rs b/crates/shoji/src/types/basic/token.rs
similarity index 56%
rename from crates/hanashi/src/chat/types/token.rs
rename to crates/shoji/src/types/basic/token.rs
index 8dd19d3a1..5311ebb8b 100644
--- a/crates/hanashi/src/chat/types/token.rs
+++ b/crates/shoji/src/types/basic/token.rs
@@ -1,7 +1,6 @@
use std::fmt;
use serde::{Deserialize, Serialize};
-use token_stream_parser::types::Token as ParserToken;
pub type TokenId = u32;
pub type TokenValue = String;
@@ -24,23 +23,3 @@ impl fmt::Display for Token {
write!(formatter, "{escaped}")
}
}
-
-impl From<ParserToken> for Token {
- fn from(token: ParserToken) -> Self {
- Self {
- id: token.id,
- value: token.value,
- is_special: token.is_special,
- }
- }
-}
-
-impl From<Token> for ParserToken {
- fn from(token: Token) -> Self {
- Self {
- id: token.id,
- value: token.value,
- is_special: token.is_special,
- }
- }
-}
diff --git a/crates/hanashi/src/chat/types/value.rs b/crates/shoji/src/types/basic/value.rs
similarity index 100%
rename from crates/hanashi/src/chat/types/value.rs
rename to crates/shoji/src/types/basic/value.rs
diff --git a/crates/hanashi/src/chat/types/capabilities.rs b/crates/shoji/src/types/chat/capabilities.rs
similarity index 100%
rename from crates/hanashi/src/chat/types/capabilities.rs
rename to crates/shoji/src/types/chat/capabilities.rs
diff --git a/crates/hanashi/src/chat/types/content_block.rs b/crates/shoji/src/types/chat/content_block.rs
similarity index 98%
rename from crates/hanashi/src/chat/types/content_block.rs
rename to crates/shoji/src/types/chat/content_block.rs
index 10429126e..b70bebc66 100644
--- a/crates/hanashi/src/chat/types/content_block.rs
+++ b/crates/shoji/src/types/chat/content_block.rs
@@ -5,7 +5,7 @@ use std::{
use serde::{Deserialize, Deserializer, Serialize, Serializer, de};
-use crate::chat::types::{ReasoningEffort, ToolCall, ToolNamespace, TranslationInput, Value};
+use crate::types::{ReasoningEffort, ToolCall, ToolNamespace, TranslationInput, Value};
#[bindings::export(Enum)]
#[derive(Debug, Clone, PartialEq, Eq, Hash)]
diff --git a/crates/hanashi/src/chat/types/message.rs b/crates/shoji/src/types/chat/message.rs
similarity index 85%
rename from crates/hanashi/src/chat/types/message.rs
rename to crates/shoji/src/types/chat/message.rs
index 1647e0863..743842b3b 100644
--- a/crates/hanashi/src/chat/types/message.rs
+++ b/crates/shoji/src/types/chat/message.rs
@@ -2,7 +2,7 @@ use std::collections::HashMap;
use serde::{Deserialize, Serialize};
-use crate::chat::types::{ContentBlock, Role, Value};
+use crate::types::{ContentBlock, Role, Value};
#[bindings::export(Struct)]
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
diff --git a/crates/hanashi/src/chat/types/mod.rs b/crates/shoji/src/types/chat/mod.rs
similarity index 86%
rename from crates/hanashi/src/chat/types/mod.rs
rename to crates/shoji/src/types/chat/mod.rs
index 30e57b463..32b790ae2 100644
--- a/crates/hanashi/src/chat/types/mod.rs
+++ b/crates/shoji/src/types/chat/mod.rs
@@ -3,23 +3,19 @@ mod content_block;
mod message;
mod reasoning_effort;
mod role;
-mod token;
mod tool_call;
mod tool_description;
mod tool_function;
mod tool_namespace;
mod translation_input;
-mod value;
pub use capabilities::Capabilities;
pub use content_block::{ContentBlock, ContentBlockType};
pub use message::Message;
pub use reasoning_effort::ReasoningEffort;
pub use role::Role;
-pub use token::{Token, TokenId, TokenValue};
pub use tool_call::ToolCall;
pub use tool_description::ToolDescription;
pub use tool_function::ToolFunction;
pub use tool_namespace::ToolNamespace;
pub use translation_input::TranslationInput;
-pub use value::Value;
diff --git a/crates/hanashi/src/chat/types/reasoning_effort.rs b/crates/shoji/src/types/chat/reasoning_effort.rs
similarity index 100%
rename from crates/hanashi/src/chat/types/reasoning_effort.rs
rename to crates/shoji/src/types/chat/reasoning_effort.rs
diff --git a/crates/hanashi/src/chat/types/role.rs b/crates/shoji/src/types/chat/role.rs
similarity index 100%
rename from crates/hanashi/src/chat/types/role.rs
rename to crates/shoji/src/types/chat/role.rs
diff --git a/crates/hanashi/src/chat/types/tool_call.rs b/crates/shoji/src/types/chat/tool_call.rs
similarity index 88%
rename from crates/hanashi/src/chat/types/tool_call.rs
rename to crates/shoji/src/types/chat/tool_call.rs
index 500f6518b..d0dd4519d 100644
--- a/crates/hanashi/src/chat/types/tool_call.rs
+++ b/crates/shoji/src/types/chat/tool_call.rs
@@ -1,6 +1,6 @@
use serde::{Deserialize, Serialize};
-use crate::chat::types::Value;
+use crate::types::Value;
#[bindings::export(Struct)]
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
diff --git a/crates/hanashi/src/chat/types/tool_description.rs b/crates/shoji/src/types/chat/tool_description.rs
similarity index 87%
rename from crates/hanashi/src/chat/types/tool_description.rs
rename to crates/shoji/src/types/chat/tool_description.rs
index 38640df35..a2777cc20 100644
--- a/crates/hanashi/src/chat/types/tool_description.rs
+++ b/crates/shoji/src/types/chat/tool_description.rs
@@ -1,6 +1,6 @@
use serde::{Deserialize, Serialize};
-use crate::chat::types::ToolFunction;
+use crate::types::ToolFunction;
#[bindings::export(Enum)]
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
diff --git a/crates/hanashi/src/chat/types/tool_function.rs b/crates/shoji/src/types/chat/tool_function.rs
similarity index 90%
rename from crates/hanashi/src/chat/types/tool_function.rs
rename to crates/shoji/src/types/chat/tool_function.rs
index 0609e7aec..9f86aff28 100644
--- a/crates/hanashi/src/chat/types/tool_function.rs
+++ b/crates/shoji/src/types/chat/tool_function.rs
@@ -1,6 +1,6 @@
use serde::{Deserialize, Serialize};
-use crate::chat::types::Value;
+use crate::types::Value;
#[bindings::export(Struct)]
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
diff --git a/crates/hanashi/src/chat/types/tool_namespace.rs b/crates/shoji/src/types/chat/tool_namespace.rs
similarity index 87%
rename from crates/hanashi/src/chat/types/tool_namespace.rs
rename to crates/shoji/src/types/chat/tool_namespace.rs
index 70393786e..45868863f 100644
--- a/crates/hanashi/src/chat/types/tool_namespace.rs
+++ b/crates/shoji/src/types/chat/tool_namespace.rs
@@ -1,6 +1,6 @@
use serde::{Deserialize, Serialize};
-use crate::chat::types::ToolDescription;
+use crate::types::ToolDescription;
#[bindings::export(Struct)]
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
diff --git a/crates/hanashi/src/chat/types/translation_input.rs b/crates/shoji/src/types/chat/translation_input.rs
similarity index 100%
rename from crates/hanashi/src/chat/types/translation_input.rs
rename to crates/shoji/src/types/chat/translation_input.rs
diff --git a/crates/shoji/src/types/mod.rs b/crates/shoji/src/types/mod.rs
new file mode 100644
index 000000000..800f82e3c
--- /dev/null
+++ b/crates/shoji/src/types/mod.rs
@@ -0,0 +1,9 @@
+mod basic;
+mod chat;
+mod model;
+mod session;
+
+pub use basic::*;
+pub use chat::*;
+pub use model::*;
+pub use session::*;
diff --git a/crates/nagare/src/registry/types/accessibility.rs b/crates/shoji/src/types/model/accessibility.rs
similarity index 59%
rename from crates/nagare/src/registry/types/accessibility.rs
rename to crates/shoji/src/types/model/accessibility.rs
index 0446a6c3f..4cd5372aa 100644
--- a/crates/nagare/src/registry/types/accessibility.rs
+++ b/crates/shoji/src/types/model/accessibility.rs
@@ -1,16 +1,15 @@
use serde::{Deserialize, Serialize};
-use crate::registry::types::{Reference, Repository};
+use crate::types::{Reference, Repository};
+#[bindings::export(Enum)]
#[derive(Debug, Clone, PartialEq, Eq, Hash, Serialize, Deserialize)]
#[serde(tag = "type", rename_all = "snake_case")]
pub enum Accessibility {
Local {
- provider_identifier: String,
reference: Reference,
},
Remote {
- provider_identifier: String,
- source_repository: Option<Repository>,
+ repository: Option<Repository>,
},
}
diff --git a/crates/nagare/src/registry/types/entity.rs b/crates/shoji/src/types/model/entity.rs
similarity index 60%
rename from crates/nagare/src/registry/types/entity.rs
rename to crates/shoji/src/types/model/entity.rs
index cdb5dc347..e4a9807c3 100644
--- a/crates/nagare/src/registry/types/entity.rs
+++ b/crates/shoji/src/types/model/entity.rs
@@ -1,21 +1,27 @@
use serde::{Deserialize, Serialize};
-use crate::registry::types::Image;
+use crate::types::Image;
+#[bindings::export(Enum)]
#[derive(Debug, Clone, PartialEq, Eq, Hash, Serialize, Deserialize)]
-#[serde(tag = "type", rename_all = "snake_case")]
+#[serde(rename_all = "snake_case")]
pub enum EntityType {
+ Registry,
+ Backend,
Vendor,
Family,
- Model,
+ Variant,
}
+#[bindings::export(Struct)]
#[derive(Debug, Clone, PartialEq, Eq, Hash, Serialize, Deserialize)]
#[serde(rename_all = "snake_case")]
pub struct Entity {
pub r#type: EntityType,
pub identifier: String,
+ pub parent_identifier: Option<String>,
pub name: String,
pub description: Option<String>,
- pub icon: Vec<Image>,
+ pub version: Option<String>,
+ pub icons: Vec<Image>,
}
diff --git a/crates/nagare/src/registry/types/file.rs b/crates/shoji/src/types/model/file.rs
similarity index 82%
rename from crates/nagare/src/registry/types/file.rs
rename to crates/shoji/src/types/model/file.rs
index 4e9ad3df5..8ac7457d8 100644
--- a/crates/nagare/src/registry/types/file.rs
+++ b/crates/shoji/src/types/model/file.rs
@@ -1,13 +1,14 @@
use serde::{Deserialize, Serialize};
-use crate::registry::types::{Hash, HashMethod};
+use crate::types::{Hash, HashMethod};
+#[bindings::export(Struct)]
#[derive(Debug, Clone, PartialEq, Eq, Hash, Serialize, Deserialize)]
#[serde(rename_all = "snake_case")]
pub struct File {
pub url: String,
pub name: String,
- pub size: u64,
+ pub size: i64,
pub hashes: Vec<Hash>,
}
diff --git a/crates/nagare/src/registry/types/hash.rs b/crates/shoji/src/types/model/hash.rs
similarity index 68%
rename from crates/nagare/src/registry/types/hash.rs
rename to crates/shoji/src/types/model/hash.rs
index e7b58c8f2..c1b383df1 100644
--- a/crates/nagare/src/registry/types/hash.rs
+++ b/crates/shoji/src/types/model/hash.rs
@@ -1,12 +1,16 @@
use serde::{Deserialize, Serialize};
+#[bindings::export(Enum)]
#[derive(Debug, Clone, PartialEq, Eq, Hash, Serialize, Deserialize)]
-#[serde(tag = "type", rename_all = "snake_case")]
+#[serde(rename_all = "snake_case")]
pub enum HashMethod {
+ #[serde(rename = "crc32c")]
CRC32C,
+ #[serde(rename = "md5")]
MD5,
}
+#[bindings::export(Struct)]
#[derive(Debug, Clone, PartialEq, Eq, Hash, Serialize, Deserialize)]
#[serde(rename_all = "snake_case")]
pub struct Hash {
diff --git a/crates/shoji/src/types/model/image.rs b/crates/shoji/src/types/model/image.rs
new file mode 100644
index 000000000..ffaedb310
--- /dev/null
+++ b/crates/shoji/src/types/model/image.rs
@@ -0,0 +1,31 @@
+use serde::{Deserialize, Serialize};
+
+#[bindings::export(Enum)]
+#[derive(Debug, Clone, PartialEq, Eq, Hash, Serialize, Deserialize)]
+#[serde(rename_all = "snake_case")]
+pub enum ImageFormat {
+ Png,
+ Webp,
+ Svg,
+}
+
+#[bindings::export(Enum)]
+#[derive(Debug, Clone, PartialEq, Eq, Hash, Serialize, Deserialize)]
+#[serde(rename_all = "snake_case")]
+pub enum ImageTheme {
+ Light,
+ Dark,
+}
+
+#[bindings::export(Struct)]
+#[derive(Debug, Clone, PartialEq, Eq, Hash, Serialize, Deserialize)]
+#[serde(rename_all = "snake_case")]
+pub struct Image {
+ pub id: String,
+ pub url: String,
+ pub theme: ImageTheme,
+ pub format: ImageFormat,
+ pub description: Option<String>,
+ pub width: Option<u32>,
+ pub height: Option<u32>,
+}
diff --git a/crates/nagare/src/registry/types/mod.rs b/crates/shoji/src/types/model/mod.rs
similarity index 78%
rename from crates/nagare/src/registry/types/mod.rs
rename to crates/shoji/src/types/model/mod.rs
index d843d964c..0adde5ff9 100644
--- a/crates/nagare/src/registry/types/mod.rs
+++ b/crates/shoji/src/types/model/mod.rs
@@ -4,6 +4,7 @@ mod file;
mod hash;
mod image;
mod model;
+mod quantization;
mod reference;
mod repository;
mod specialization;
@@ -12,8 +13,9 @@ pub use accessibility::Accessibility;
pub use entity::{Entity, EntityType};
pub use file::File;
pub use hash::{Hash, HashMethod};
-pub use image::Image;
+pub use image::{Image, ImageFormat, ImageTheme};
pub use model::Model;
+pub use quantization::Quantization;
pub use reference::Reference;
pub use repository::Repository;
pub use specialization::Specialization;
diff --git a/crates/nagare/src/registry/types/model.rs b/crates/shoji/src/types/model/model.rs
similarity index 67%
rename from crates/nagare/src/registry/types/model.rs
rename to crates/shoji/src/types/model/model.rs
index 5e5099abf..0e7ecd18a 100644
--- a/crates/nagare/src/registry/types/model.rs
+++ b/crates/shoji/src/types/model/model.rs
@@ -1,23 +1,26 @@
use serde::{Deserialize, Serialize};
-use crate::registry::types::{Accessibility, Entity, Reference, Specialization};
+use crate::types::{Accessibility, Entity, EntityType, Quantization, Reference, Specialization};
-#[derive(Debug, Clone, PartialEq, Eq, Hash, Serialize, Deserialize)]
+#[bindings::export(Struct)]
+#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
#[serde(rename_all = "snake_case")]
pub struct Model {
+ pub identifier: String,
pub entities: Vec<Entity>,
pub specializations: Vec<Specialization>,
- pub number_of_parameters: Option<u64>,
+ pub number_of_parameters: Option<i64>,
+ pub quantization: Option<Quantization>,
pub accessibility: Accessibility,
}
impl Model {
pub fn identifier(&self) -> String {
- self.entities.iter().map(|entity| entity.identifier.clone()).collect::<Vec<String>>().join(":")
+ self.identifier.clone()
}
pub fn cache_identifier(&self) -> String {
- self.identifier().replace(":", "-")
+ self.identifier.replace(":", "-")
}
pub fn is_local(&self) -> bool {
@@ -28,19 +31,6 @@ impl Model {
matches!(self.accessibility, Accessibility::Remote { .. })
}
- pub fn provider_identifier(&self) -> String {
- match &self.accessibility {
- Accessibility::Local {
- provider_identifier,
- ..
- } => provider_identifier.clone(),
- Accessibility::Remote {
- provider_identifier,
- ..
- } => provider_identifier.clone(),
- }
- }
-
pub fn repo_ids(&self) -> Vec<String> {
match &self.accessibility {
Accessibility::Local {
@@ -66,12 +56,12 @@ impl Model {
} => vec![repository.identifier.clone()],
},
Accessibility::Remote {
- source_repository,
+ repository,
..
} => {
let mut result = vec![];
- if let Some(source_repository) = source_repository {
- result.push(source_repository.identifier.clone());
+ if let Some(repository) = repository {
+ result.push(repository.identifier.clone());
}
result
},
@@ -110,3 +100,32 @@ impl Model {
}
}
}
+
+impl Model {
+ pub fn registry_entity(&self) -> Option<Entity> {
+ self.entity(EntityType::Registry)
+ }
+
+ pub fn backend_entity(&self) -> Option<Entity> {
+ self.entity(EntityType::Backend)
+ }
+
+ pub fn vendor_entity(&self) -> Option<Entity> {
+ self.entity(EntityType::Vendor)
+ }
+
+ pub fn family_entity(&self) -> Option<Entity> {
+ self.entity(EntityType::Family)
+ }
+
+ pub fn variant_entity(&self) -> Option<Entity> {
+ self.entity(EntityType::Variant)
+ }
+
+ fn entity(
+ &self,
+ r#type: EntityType,
+ ) -> Option<Entity> {
+ self.entities.iter().find(|entity| entity.r#type == r#type).map(|entity| entity.clone())
+ }
+}
diff --git a/crates/nagare/src/registry/types/image.rs b/crates/shoji/src/types/model/quantization.rs
similarity index 57%
rename from crates/nagare/src/registry/types/image.rs
rename to crates/shoji/src/types/model/quantization.rs
index fde3dd005..c1bb0d60a 100644
--- a/crates/nagare/src/registry/types/image.rs
+++ b/crates/shoji/src/types/model/quantization.rs
@@ -1,9 +1,9 @@
use serde::{Deserialize, Serialize};
+#[bindings::export(Struct)]
#[derive(Debug, Clone, PartialEq, Eq, Hash, Serialize, Deserialize)]
#[serde(rename_all = "snake_case")]
-pub struct Image {
- pub url: String,
- pub width: u32,
- pub height: u32,
+pub struct Quantization {
+ pub method: String,
+ pub bits_per_weight: u32,
}
diff --git a/crates/nagare/src/registry/types/reference.rs b/crates/shoji/src/types/model/reference.rs
similarity index 91%
rename from crates/nagare/src/registry/types/reference.rs
rename to crates/shoji/src/types/model/reference.rs
index fd02d04cd..eb3f99d5d 100644
--- a/crates/nagare/src/registry/types/reference.rs
+++ b/crates/shoji/src/types/model/reference.rs
@@ -1,7 +1,8 @@
use serde::{Deserialize, Serialize};
-use crate::registry::types::{File, Repository};
+use crate::types::{File, Repository};
+#[bindings::export(Enum)]
#[derive(Debug, Clone, PartialEq, Eq, Hash, Serialize, Deserialize)]
#[serde(tag = "type", rename_all = "snake_case")]
pub enum Reference {
diff --git a/crates/nagare/src/registry/types/repository.rs b/crates/shoji/src/types/model/repository.rs
similarity index 90%
rename from crates/nagare/src/registry/types/repository.rs
rename to crates/shoji/src/types/model/repository.rs
index c5c437ae0..7bb7e6403 100644
--- a/crates/nagare/src/registry/types/repository.rs
+++ b/crates/shoji/src/types/model/repository.rs
@@ -1,5 +1,6 @@
use serde::{Deserialize, Serialize};
+#[bindings::export(Struct)]
#[derive(Debug, Clone, PartialEq, Eq, Hash, Serialize, Deserialize)]
#[serde(rename_all = "snake_case")]
pub struct Repository {
diff --git a/crates/nagare/src/registry/types/specialization.rs b/crates/shoji/src/types/model/specialization.rs
similarity index 91%
rename from crates/nagare/src/registry/types/specialization.rs
rename to crates/shoji/src/types/model/specialization.rs
index 44bfefdc5..9cfabe58a 100644
--- a/crates/nagare/src/registry/types/specialization.rs
+++ b/crates/shoji/src/types/model/specialization.rs
@@ -1,5 +1,6 @@
use serde::{Deserialize, Serialize};
+#[bindings::export(Enum)]
#[derive(Debug, Clone, PartialEq, Eq, Hash, Serialize, Deserialize)]
#[serde(tag = "type", rename_all = "snake_case")]
pub enum Specialization {
diff --git a/crates/shoji/src/types/session/classification_feature.rs b/crates/shoji/src/types/session/classification_feature.rs
new file mode 100644
index 000000000..f60698022
--- /dev/null
+++ b/crates/shoji/src/types/session/classification_feature.rs
@@ -0,0 +1,8 @@
+use serde::{Deserialize, Serialize};
+
+#[bindings::export(Struct)]
+#[derive(Debug, Clone, PartialEq, Eq, Hash, Serialize, Deserialize)]
+pub struct ClassificationFeature {
+ pub name: String,
+ pub values: Vec<String>,
+}
diff --git a/crates/shoji/src/types/session/mod.rs b/crates/shoji/src/types/session/mod.rs
new file mode 100644
index 000000000..83eefede0
--- /dev/null
+++ b/crates/shoji/src/types/session/mod.rs
@@ -0,0 +1,3 @@
+mod classification_feature;
+
+pub use classification_feature::ClassificationFeature;
diff --git a/crates/uzu/Cargo.toml b/crates/uzu/Cargo.toml
index 202d93560..121f1147b 100644
--- a/crates/uzu/Cargo.toml
+++ b/crates/uzu/Cargo.toml
@@ -7,21 +7,82 @@ license.workspace = true
authors.workspace = true
repository.workspace = true
+[lib]
+crate-type = ["lib", "cdylib", "staticlib"]
+
+[features]
+default = ["metal", "grammar"]
+metal = ["backend-uzu/metal"]
+grammar = ["backend-uzu/grammar"]
+tracing = ["backend-uzu/tracing"]
+bindings = [
+ "bindings-uniffi",
+ "bindings-napi",
+ "bindings-pyo3",
+ "bindings-wasm",
+]
+bindings-uniffi = ["shoji/bindings-uniffi", "dep:uniffi"]
+bindings-napi = [
+ "shoji/bindings-napi",
+ "dep:napi",
+ "dep:napi-derive",
+ "dep:napi-build",
+]
+bindings-pyo3 = ["shoji/bindings-pyo3", "dep:pyo3"]
+bindings-wasm = [
+ "shoji/bindings-wasm",
+ "dep:wasm-bindgen",
+ "dep:serde-wasm-bindgen",
+ "dep:wasm-bindgen-futures",
+ "dep:tsify",
+]
+
[dependencies]
+bindings.workspace = true
backend-uzu.workspace = true
+shoji.workspace = true
+uniffi = { workspace = true, optional = true }
+napi = { workspace = true, optional = true }
+napi-derive = { workspace = true, optional = true }
+pyo3 = { workspace = true, optional = true }
+wasm-bindgen = { workspace = true, optional = true }
+serde-wasm-bindgen = { workspace = true, optional = true }
+wasm-bindgen-futures = { workspace = true, optional = true }
+tsify = { workspace = true, optional = true }
[target.'cfg(not(target_family = "wasm"))'.dependencies]
nagare.workspace = true
+download-manager.workspace = true
serde.workspace = true
+serde_json.workspace = true
thiserror.workspace = true
+futures.workspace = true
tokio.workspace = true
tokio-stream.workspace = true
+dirs.workspace = true
+sysinfo.workspace = true
+reqwest.workspace = true
+indexmap.workspace = true
+tracing.workspace = true
+tracing-subscriber.workspace = true
+tracing-appender.workspace = true
+uuid.workspace = true
+futures-util.workspace = true
+openai-api-rs.workspace = true
+regex.workspace = true
+
+[target.'cfg(target_vendor = "apple")'.dependencies]
+objc2.workspace = true
+objc2-foundation.workspace = true
+objc2-security.workspace = true
[dev-dependencies]
+tracing-subscriber.workspace = true
+tracing-appender.workspace = true
+chrono.workspace = true
+tempfile.workspace = true
+indicatif.workspace = true
dotenvy.workspace = true
-[features]
-default = ["metal", "grammar"]
-metal = ["backend-uzu/metal"]
-grammar = ["backend-uzu/grammar"]
-tracing = ["backend-uzu/tracing"]
+[build-dependencies]
+napi-build = { workspace = true, optional = true }
diff --git a/crates/uzu/build.rs b/crates/uzu/build.rs
new file mode 100644
index 000000000..6de3825da
--- /dev/null
+++ b/crates/uzu/build.rs
@@ -0,0 +1,4 @@
+fn main() {
+ #[cfg(feature = "bindings-napi")]
+ napi_build::setup();
+}
diff --git a/crates/nagare/src/device/error.rs b/crates/uzu/src/device/error.rs
similarity index 100%
rename from crates/nagare/src/device/error.rs
rename to crates/uzu/src/device/error.rs
diff --git a/crates/nagare/src/device/mod.rs b/crates/uzu/src/device/mod.rs
similarity index 100%
rename from crates/nagare/src/device/mod.rs
rename to crates/uzu/src/device/mod.rs
diff --git a/crates/nagare/src/device/os.rs b/crates/uzu/src/device/os.rs
similarity index 100%
rename from crates/nagare/src/device/os.rs
rename to crates/uzu/src/device/os.rs
diff --git a/crates/uzu/src/engine/config.rs b/crates/uzu/src/engine/config.rs
index df2b6b75c..4eeaf207c 100644
--- a/crates/uzu/src/engine/config.rs
+++ b/crates/uzu/src/engine/config.rs
@@ -2,12 +2,16 @@ use std::env;
use serde::{Deserialize, Serialize};
+#[bindings::export(Struct)]
#[derive(Debug, Clone, PartialEq, Eq, Hash, Serialize, Deserialize)]
#[serde(rename_all = "snake_case")]
pub struct Config {
pub mirai_api_key: Option<String>,
pub huggingface_api_key: Option<String>,
pub openai_api_key: Option<String>,
+ pub baseten_api_key: Option<String>,
+ pub anthropic_api_key: Option<String>,
+ pub openrouter_api_key: Option<String>,
}
impl Default for Config {
@@ -16,6 +20,9 @@ impl Default for Config {
mirai_api_key: env::var("MIRAI_API_KEY").ok(),
huggingface_api_key: env::var("HF_TOKEN").ok(),
openai_api_key: env::var("OPENAI_API_KEY").ok(),
+ baseten_api_key: env::var("BASETEN_API_KEY").ok(),
+ anthropic_api_key: env::var("ANTHROPIC_API_KEY").ok(),
+ openrouter_api_key: env::var("OPENROUTER_API_KEY").ok(),
}
}
}
@@ -44,4 +51,28 @@ impl Config {
self.openai_api_key = Some(openai_api_key);
self
}
+
+ pub fn with_baseten_api_key(
+ mut self,
+ baseten_api_key: String,
+ ) -> Self {
+ self.baseten_api_key = Some(baseten_api_key);
+ self
+ }
+
+ pub fn with_anthropic_api_key(
+ mut self,
+ anthropic_api_key: String,
+ ) -> Self {
+ self.anthropic_api_key = Some(anthropic_api_key);
+ self
+ }
+
+ pub fn with_openrouter_api_key(
+ mut self,
+ openrouter_api_key: String,
+ ) -> Self {
+ self.openrouter_api_key = Some(openrouter_api_key);
+ self
+ }
}
diff --git a/crates/uzu/src/engine/downloader.rs b/crates/uzu/src/engine/downloader.rs
index f1eb7b6aa..73ec8f0b5 100644
--- a/crates/uzu/src/engine/downloader.rs
+++ b/crates/uzu/src/engine/downloader.rs
@@ -1,13 +1,13 @@
-use nagare::{
+use tokio_stream::{StreamExt, wrappers::BroadcastStream};
+
+use crate::{
+ engine::Error,
helpers::SharedAccess,
storage::{
Error as StorageError, Storage,
types::{DownloadPhase, DownloadState},
},
};
-use tokio_stream::{StreamExt, wrappers::BroadcastStream};
-
-use crate::engine::Error;
pub struct Downloader {
identifier: String,
diff --git a/crates/uzu/src/engine/error.rs b/crates/uzu/src/engine/error.rs
index ebb27c29d..2f283f9ac 100644
--- a/crates/uzu/src/engine/error.rs
+++ b/crates/uzu/src/engine/error.rs
@@ -6,9 +6,13 @@ pub enum Error {
message: String,
},
#[error(transparent)]
- Device(#[from] nagare::device::Error),
+ Device(#[from] crate::device::Error),
#[error(transparent)]
- Storage(#[from] nagare::storage::Error),
+ Storage(#[from] crate::storage::Error),
#[error(transparent)]
- Registry(#[from] nagare::registry::Error),
+ Registry(#[from] crate::registry::Error),
+ #[error("Backend error: {message}")]
+ Backend {
+ message: String,
+ },
}
diff --git a/crates/uzu/src/engine/mod.rs b/crates/uzu/src/engine/mod.rs
index 6578e21bc..aea1d399c 100644
--- a/crates/uzu/src/engine/mod.rs
+++ b/crates/uzu/src/engine/mod.rs
@@ -2,43 +2,100 @@ mod config;
mod downloader;
mod error;
+use std::collections::HashMap;
+
+use backend_uzu::inference_backend::{Backend as UzuBackend, Config as UzuBackendConfig};
pub use config::Config;
pub use downloader::Downloader;
pub use error::Error;
-use nagare::{
- device::Device,
- helpers::SharedAccess,
- registry::{CachedRegistry, MergedRegistry, Registry, types::Model},
- storage::{Config as StorageConfig, Storage},
+use shoji::{
+ traits::{Backend, BackendInstance, Registry},
+ types::Model,
};
use tokio::runtime::Handle;
+use tokio_stream::wrappers::BroadcastStream;
+
+use crate::{
+ device::Device,
+ helpers::{SharedAccess, is_endpoint_reachable},
+ logs,
+ registry::{
+ CachedRegistry, Error as RegistryError, MergedRegistry,
+ mirai::{Backend as MiraiBackend, Config as MiraiRegistryConfig, Registry as MiraiRegistry},
+ openai::{Config as OpenAIConfig, Registry as OpenAIRegistry},
+ },
+ storage::{Config as StorageConfig, Storage, types::DownloadState},
+};
pub struct Engine {
registry: SharedAccess<MergedRegistry>,
storage: SharedAccess<Storage>,
+ backends: HashMap<String, Box<dyn Backend>>,
}
impl Engine {
- pub async fn new(_config: Config) -> Result<Self, Error> {
+ pub async fn new(config: Config) -> Result<Self, Error> {
let tokio_handle = Handle::try_current().map_err(|error| Error::TokioError {
message: error.to_string(),
})?;
let device = Device::new()?;
let registry = SharedAccess::new(MergedRegistry::new(vec![]));
- let storage = SharedAccess::new(
- Storage::new(tokio_handle.clone(), StorageConfig::new(device.clone(), None, "mirai".to_string())).await?,
- );
+ let storage_config = StorageConfig::new(device.clone(), None, "mirai".to_string());
+ logs::start(storage_config.cache_path(), &storage_config.log_name(), false);
+
+ let storage = SharedAccess::new(Storage::new(tokio_handle.clone(), storage_config).await?);
- let engine = Self {
+ let uzu_backend_config = UzuBackendConfig {};
+ let uzu_backend: Box<dyn Backend> =
+ Box::new(UzuBackend::new(uzu_backend_config).map_err(|error| Error::Backend {
+ message: error.to_string(),
+ })?);
+
+ let mirai_registry_config = MiraiRegistryConfig {
+ api_key: config.mirai_api_key,
+ device: device.clone(),
+ backends: vec![MiraiBackend {
+ identifier: uzu_backend.identifier(),
+ version: uzu_backend.version(),
+ }],
+ include_traces: false,
+ };
+ let mirai_registry = Box::new(MiraiRegistry::new(mirai_registry_config)?);
+
+ let mut engine = Self {
storage,
registry,
+ backends: HashMap::new(),
};
+ engine.add_backend(uzu_backend);
+ engine.add_registry(mirai_registry).await?;
+
+ if let Some(openai_api_key) = config.openai_api_key {
+ let openai_registry = OpenAIRegistry::new(OpenAIConfig::openai(openai_api_key))?;
+ engine.add_registry(Box::new(openai_registry)).await?;
+ }
+
+ let ollama_config = OpenAIConfig::ollama();
+ if is_endpoint_reachable(&ollama_config.api_endpoint).await {
+ let ollama_registry = OpenAIRegistry::new(ollama_config)?;
+ engine.add_registry(Box::new(ollama_registry)).await?;
+ }
- // if let Some(openai_api_key) = config.openai_api_key {
- // let openai_registry = OpenAIRegistry::new(OpenAIConfig::openai(openai_api_key))?;
- // engine.add_registry(Box::new(openai_registry)).await?;
- // }
+ if let Some(baseten_api_key) = config.baseten_api_key {
+ let baseten_registry = OpenAIRegistry::new(OpenAIConfig::baseten(baseten_api_key))?;
+ engine.add_registry(Box::new(baseten_registry)).await?;
+ }
+
+ if let Some(anthropic_api_key) = config.anthropic_api_key {
+ let anthropic_registry = OpenAIRegistry::new(OpenAIConfig::anthropic(anthropic_api_key))?;
+ engine.add_registry(Box::new(anthropic_registry)).await?;
+ }
+
+ if let Some(openrouter_api_key) = config.openrouter_api_key {
+ let openrouter_registry = OpenAIRegistry::new(OpenAIConfig::openrouter(openrouter_api_key))?;
+ engine.add_registry(Box::new(openrouter_registry)).await?;
+ }
Ok(engine)
}
@@ -47,7 +104,7 @@ impl Engine {
impl Engine {
pub async fn add_registry(
&self,
- registry: Box<dyn Registry>,
+ registry: Box<dyn Registry<Error = RegistryError>>,
) -> Result<(), Error> {
self.registry.lock().await.add(Box::new(CachedRegistry::new(registry)))?;
self.handle_registry_resfresh().await?;
@@ -64,6 +121,22 @@ impl Engine {
}
}
+impl Engine {
+ pub fn add_backend(
+ &mut self,
+ backend: Box<dyn Backend>,
+ ) {
+ self.backends.insert(backend.identifier(), backend);
+ }
+
+ pub fn remove_backend(
+ &mut self,
+ identifier: &str,
+ ) {
+ self.backends.remove(identifier);
+ }
+}
+
impl Engine {
pub async fn models(&self) -> Result<Vec<Model>, Error> {
self.registry.lock().await.models().await.map_err(Error::from)
@@ -92,6 +165,10 @@ impl Engine {
Downloader::new(model.identifier(), self.storage.clone())
}
+ pub async fn storage_subscribe(&self) -> BroadcastStream<(String, DownloadState)> {
+ self.storage.lock().await.subscribe()
+ }
+
async fn handle_registry_resfresh(&self) -> Result<(), Error> {
let models = self.registry.lock().await.models().await?;
self.storage.lock().await.refresh(models).await?;
diff --git a/crates/uzu/src/helpers/mod.rs b/crates/uzu/src/helpers/mod.rs
new file mode 100644
index 000000000..b2f7b0f8e
--- /dev/null
+++ b/crates/uzu/src/helpers/mod.rs
@@ -0,0 +1,5 @@
+mod reachability;
+mod shared_access;
+
+pub use reachability::is_endpoint_reachable;
+pub use shared_access::SharedAccess;
diff --git a/crates/uzu/src/helpers/reachability.rs b/crates/uzu/src/helpers/reachability.rs
new file mode 100644
index 000000000..3c5a0c1db
--- /dev/null
+++ b/crates/uzu/src/helpers/reachability.rs
@@ -0,0 +1,21 @@
+use std::time::Duration;
+
+use reqwest::Url;
+use tokio::{net::TcpStream, time::timeout};
+
+pub async fn is_endpoint_reachable(endpoint: &str) -> bool {
+ let Some(url) = Url::parse(endpoint).ok() else {
+ return false;
+ };
+ let Some(host) = url.host_str().map(|host| host.to_string()) else {
+ return false;
+ };
+ let Some(port) = url.port_or_known_default().map(|port| port) else {
+ return false;
+ };
+
+ timeout(Duration::from_millis(200), TcpStream::connect((host, port)))
+ .await
+ .map(|result| result.is_ok())
+ .unwrap_or(false)
+}
diff --git a/crates/nagare/src/helpers/shared_access.rs b/crates/uzu/src/helpers/shared_access.rs
similarity index 100%
rename from crates/nagare/src/helpers/shared_access.rs
rename to crates/uzu/src/helpers/shared_access.rs
diff --git a/crates/uzu/src/lib.rs b/crates/uzu/src/lib.rs
index 5a6e15633..fdc2767d0 100644
--- a/crates/uzu/src/lib.rs
+++ b/crates/uzu/src/lib.rs
@@ -1,4 +1,19 @@
+#[cfg(feature = "bindings-uniffi")]
+shoji::uniffi_reexport_scaffolding!();
+#[cfg(feature = "bindings-uniffi")]
+uniffi::setup_scaffolding!();
+
+#[cfg(not(target_family = "wasm"))]
+pub mod device;
#[cfg(not(target_family = "wasm"))]
pub mod engine;
+#[cfg(not(target_family = "wasm"))]
+pub mod helpers;
+#[cfg(not(target_family = "wasm"))]
+pub mod logs;
+#[cfg(not(target_family = "wasm"))]
+pub mod registry;
+#[cfg(not(target_family = "wasm"))]
+pub mod storage;
pub use backend_uzu::*;
diff --git a/crates/uzu/src/logs/mod.rs b/crates/uzu/src/logs/mod.rs
new file mode 100644
index 000000000..6b8c5152b
--- /dev/null
+++ b/crates/uzu/src/logs/mod.rs
@@ -0,0 +1,116 @@
+use std::{
+ fs::{self, File, OpenOptions},
+ io::{BufRead, BufReader, Write},
+ path::PathBuf,
+ sync::Once,
+};
+
+use tracing_subscriber::{EnvFilter, fmt, layer::SubscriberExt, util::SubscriberInitExt};
+
+static INIT: Once = Once::new();
+
+const MAX_LOG_SIZE_BYTES: u64 = 10 * 1024 * 1024;
+const KEEP_LINES: usize = 5000;
+
+/// Initialize tracing for production use
+/// Logs are written to a single file that gets trimmed when it exceeds MAX_LOG_SIZE_BYTES
+/// Keeps only the last KEEP_LINES lines when trimming
+pub fn start(
+ path: PathBuf,
+ name: &str,
+ stdout: bool,
+) {
+ INIT.call_once(|| {
+ init(path, name, MAX_LOG_SIZE_BYTES, KEEP_LINES, stdout);
+ });
+}
+
+fn init(
+ path: PathBuf,
+ name: &str,
+ max_size_bytes: u64,
+ keep_lines: usize,
+ also_stdout: bool,
+) {
+ if let Err(e) = fs::create_dir_all(&path) {
+ eprintln!("Failed to create log directory {:?}: {}", path, e);
+ return;
+ }
+
+ let log_file_path = path.join(name);
+ // Spawn trimming worker
+ start_trim_thread(log_file_path.clone(), max_size_bytes, keep_lines);
+
+ // File appender (no built-in rotation)
+ let file_appender = tracing_appender::rolling::never(&path, name);
+ let (non_blocking, guard) = tracing_appender::non_blocking(file_appender);
+ // Keep guard alive for the process lifetime
+ std::mem::forget(guard);
+
+ let env_filter = EnvFilter::try_from_default_env()
+ .or_else(|_| EnvFilter::try_new("info"))
+ .unwrap_or_else(|_| EnvFilter::new("info"));
+
+ let registry = tracing_subscriber::registry().with(env_filter).with(
+ fmt::layer()
+ .with_writer(non_blocking)
+ .with_ansi(false)
+ .with_target(true)
+ .with_thread_ids(true)
+ .with_line_number(true),
+ );
+
+ if also_stdout {
+ registry.with(fmt::layer().with_writer(std::io::stdout)).init();
+ } else {
+ registry.init();
+ }
+}
+
+fn trim_log_file(
+ log_path: &PathBuf,
+ keep_lines: usize,
+) -> std::io::Result<()> {
+ let file = File::open(log_path)?;
+ let reader = BufReader::new(file);
+ let lines: Vec<String> = reader
+ .lines()
+ .filter_map(Result::ok)
+ .collect::<Vec<_>>()
+ .into_iter()
+ .rev()
+ .take(keep_lines)
+ .collect::<Vec<_>>()
+ .into_iter()
+ .rev()
+ .collect();
+
+ let temp_path = log_path.with_extension("log.tmp");
+ let mut temp_file = OpenOptions::new().write(true).create(true).truncate(true).open(&temp_path)?;
+
+ for line in lines {
+ writeln!(temp_file, "{}", line)?;
+ }
+ temp_file.sync_all()?;
+ drop(temp_file);
+
+ fs::rename(&temp_path, log_path)?;
+ Ok(())
+}
+
+fn start_trim_thread(
+ log_path: PathBuf,
+ max_size_bytes: u64,
+ keep_lines: usize,
+) {
+ std::thread::spawn(move || {
+ loop {
+ std::thread::sleep(std::time::Duration::from_secs(60));
+ if let Ok(metadata) = fs::metadata(&log_path) {
+ if metadata.len() > max_size_bytes {
+ let _ = trim_log_file(&log_path, keep_lines);
+ }
+ }
+ }
+ });
+}
diff --git a/crates/nagare/src/registry/cached.rs b/crates/uzu/src/registry/cached.rs
similarity index 82%
rename from crates/nagare/src/registry/cached.rs
rename to crates/uzu/src/registry/cached.rs
index a07bd973c..ee8c1e4f8 100644
--- a/crates/nagare/src/registry/cached.rs
+++ b/crates/uzu/src/registry/cached.rs
@@ -1,16 +1,17 @@
use std::{future::Future, pin::Pin};
+use shoji::{traits::Registry, types::Model};
use tokio::sync::Mutex;
-use crate::registry::{Error, Registry, types::Model};
+use crate::registry::Error;
pub struct CachedRegistry {
- registry: Box<dyn Registry>,
+ registry: Box<dyn Registry<Error = Error>>,
models: Mutex<Option<Vec<Model>>>,
}
impl CachedRegistry {
- pub fn new(registry: Box<dyn Registry>) -> Self {
+ pub fn new(registry: Box<dyn Registry<Error = Error>>) -> Self {
Self {
registry,
models: Mutex::new(None),
@@ -24,6 +25,8 @@ impl CachedRegistry {
}
impl Registry for CachedRegistry {
+ type Error = Error;
+
fn indentifier(&self) -> String {
self.registry.indentifier()
}
diff --git a/crates/nagare/src/registry/error.rs b/crates/uzu/src/registry/error.rs
similarity index 100%
rename from crates/nagare/src/registry/error.rs
rename to crates/uzu/src/registry/error.rs
diff --git a/crates/nagare/src/registry/fixed.rs b/crates/uzu/src/registry/fixed.rs
similarity index 87%
rename from crates/nagare/src/registry/fixed.rs
rename to crates/uzu/src/registry/fixed.rs
index 450d62b7e..cf08faa23 100644
--- a/crates/nagare/src/registry/fixed.rs
+++ b/crates/uzu/src/registry/fixed.rs
@@ -1,8 +1,9 @@
use std::{future::Future, pin::Pin};
+use shoji::{traits::Registry, types::Model};
use tokio::sync::Mutex;
-use crate::registry::{Error, Registry, types::Model};
+use crate::registry::Error;
pub struct FixedRegistry {
identifier: String,
@@ -22,6 +23,8 @@ impl FixedRegistry {
}
impl Registry for FixedRegistry {
+ type Error = Error;
+
fn indentifier(&self) -> String {
self.identifier.clone()
}
diff --git a/crates/nagare/src/registry/merged.rs b/crates/uzu/src/registry/merged.rs
similarity index 82%
rename from crates/nagare/src/registry/merged.rs
rename to crates/uzu/src/registry/merged.rs
index cd9cca874..4cbe8d694 100644
--- a/crates/nagare/src/registry/merged.rs
+++ b/crates/uzu/src/registry/merged.rs
@@ -1,13 +1,15 @@
use std::{future::Future, pin::Pin};
-use crate::registry::{Error, Registry, types::Model};
+use shoji::{traits::Registry, types::Model};
+
+use crate::registry::Error;
pub struct MergedRegistry {
- registries: Vec<Box<dyn Registry>>,
+ registries: Vec<Box<dyn Registry<Error = Error>>>,
}
impl MergedRegistry {
- pub fn new(registries: Vec<Box<dyn Registry>>) -> Self {
+ pub fn new(registries: Vec<Box<dyn Registry<Error = Error>>>) -> Self {
Self {
registries,
}
@@ -15,7 +17,7 @@ impl MergedRegistry {
pub fn add(
&mut self,
- registry: Box<dyn Registry>,
+ registry: Box<dyn Registry<Error = Error>>,
) -> Result<(), Error> {
if self.registries.iter().any(|current_registry| current_registry.indentifier() == registry.indentifier()) {
return Err(Error::UnableToAddRegistry {
@@ -36,6 +38,8 @@ impl MergedRegistry {
}
impl Registry for MergedRegistry {
+ type Error = Error;
+
fn indentifier(&self) -> String {
self.registries.iter().map(|registry| registry.indentifier()).collect::<Vec<String>>().join(":")
}
diff --git a/crates/uzu/src/registry/mirai/api.rs b/crates/uzu/src/registry/mirai/api.rs
new file mode 100644
index 000000000..db982af6b
--- /dev/null
+++ b/crates/uzu/src/registry/mirai/api.rs
@@ -0,0 +1,56 @@
+use indexmap::IndexMap;
+use nagare::api::{Config, Endpoint as EndpointTrait, Payload};
+use reqwest::{Method, header::CONTENT_TYPE};
+use serde_json::json;
+
+use crate::{device::Device, registry::mirai::config::Backend};
+
+pub enum Endpoint {
+ FetchModels {
+ device: Device,
+ backends: Vec<Backend>,
+ include_traces: bool,
+ },
+}
+
+impl EndpointTrait for Endpoint {
+ fn method(&self) -> Method {
+ match self {
+ Endpoint::FetchModels {
+ ..
+ } => Method::POST,
+ }
+ }
+
+ fn path(&self) -> String {
+ match self {
+ Endpoint::FetchModels {
+ ..
+ } => "fetch/models".to_string(),
+ }
+ }
+
+ fn headers(&self) -> IndexMap<String, String> {
+ IndexMap::from([(CONTENT_TYPE.to_string(), "application/json".to_string())])
+ }
+
+ fn payload(
+ &self,
+ _: &Config,
+ ) -> Payload {
+ match self {
+ Endpoint::FetchModels {
+ device,
+ backends,
+ include_traces,
+ } => Payload {
+ query: None,
+ body: Some(json!({
+ "device": device,
+ "backends": backends,
+ "include_traces": include_traces,
+ })),
+ },
+ }
+ }
+}
diff --git a/crates/uzu/src/registry/mirai/config.rs b/crates/uzu/src/registry/mirai/config.rs
new file mode 100644
index 000000000..75c8e432e
--- /dev/null
+++ b/crates/uzu/src/registry/mirai/config.rs
@@ -0,0 +1,35 @@
+use serde::{Deserialize, Serialize};
+
+use crate::device::Device;
+
+#[derive(Debug, Clone, PartialEq, Eq, Hash, Serialize, Deserialize)]
+#[serde(rename_all = "snake_case")]
+pub struct Backend {
+ pub identifier: String,
+ pub version: String,
+}
+
+#[derive(Debug, Clone, PartialEq, Eq, Hash, Serialize, Deserialize)]
+#[serde(rename_all = "snake_case")]
+pub struct Config {
+ pub api_key: Option<String>,
+ pub device: Device,
+ pub backends: Vec<Backend>,
+ pub include_traces: bool,
+}
+
+impl Config {
+ pub fn new(
+ api_key: Option<String>,
+ device: Device,
+ backends: Vec<Backend>,
+ include_traces: bool,
+ ) -> Self {
+ Self {
+ api_key,
+ device,
+ backends,
+ include_traces,
+ }
+ }
+}
diff --git a/crates/uzu/src/registry/mirai/mod.rs b/crates/uzu/src/registry/mirai/mod.rs
new file mode 100644
index 000000000..a022790b1
--- /dev/null
+++ b/crates/uzu/src/registry/mirai/mod.rs
@@ -0,0 +1,67 @@
+mod api;
+mod config;
+mod types;
+
+use std::{future::Future, pin::Pin, time::Duration};
+
+pub use api::Endpoint;
+pub use config::{Backend, Config};
+use indexmap::IndexMap;
+use nagare::api::{Client, Config as ClientConfig};
+use reqwest::header::AUTHORIZATION;
+use shoji::{traits::Registry as RegistryTrait, types::Model};
+pub use types::Response;
+
+use crate::registry::Error;
+
+pub struct Registry {
+ config: Config,
+ client: Client,
+}
+
+impl Registry {
+ pub fn new(config: Config) -> Result<Self, Error> {
+ let mut headers: IndexMap<String, String> = IndexMap::new();
+ if let Some(api_key) = config.api_key.clone() {
+ headers.insert(AUTHORIZATION.to_string(), format!("Bearer {}", api_key));
+ }
+
+ let client_config =
+ ClientConfig::new("https://sdk.trymirai.com/api/v1".to_string(), Duration::from_secs(10), headers);
+ let client = Client::new(client_config).map_err(|error| Error::UnableToCreate {
+ message: error.to_string(),
+ })?;
+
+ Ok(Self {
+ config,
+ client,
+ })
+ }
+}
+impl RegistryTrait for Registry {
+ type Error = Error;
+
+ fn indentifier(&self) -> String {
+ "mirai".to_string()
+ }
+
+ fn models(&self) -> Pin<Box<dyn Future<Output = Result<Vec<Model>, Error>> + Send + '_>> {
+ Box::pin(async {
+ let response: Response = self
+ .client
+ .response(&Endpoint::FetchModels {
+ device: self.config.device.clone(),
+ backends: self.config.backends.clone(),
+ include_traces: self.config.include_traces,
+ })
+ .await
+ .map_err(|error| Error::UnableToGetModels {
+ message: error.to_string(),
+ })?;
+ let models = response.models().ok_or(Error::UnableToGetModels {
+ message: "Unable to extract from response".to_string(),
+ })?;
+ Ok(models)
+ })
+ }
+}
diff --git a/crates/uzu/src/registry/mirai/types.rs b/crates/uzu/src/registry/mirai/types.rs
new file mode 100644
index 000000000..10f40e8e4
--- /dev/null
+++ b/crates/uzu/src/registry/mirai/types.rs
@@ -0,0 +1,57 @@
+use serde::{Deserialize, Serialize};
+use shoji::types::{Accessibility, Entity, Model, Quantization, Specialization};
+
+#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
+#[serde(rename_all = "snake_case")]
+struct ResponseModel {
+ pub identifier: String,
+ pub entity_identifiers: Vec<String>,
+ pub specializations: Vec<Specialization>,
+ pub number_of_parameters: Option<i64>,
+ pub quantization: Option<Quantization>,
+ pub accessibility: Accessibility,
+}
+
+#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
+#[serde(rename_all = "snake_case")]
+pub struct Response {
+ models: Vec<ResponseModel>,
+ entities: Vec<Entity>,
+}
+
+impl Response {
+ pub fn models(&self) -> Option<Vec<Model>> {
+ let models = self
+ .models
+ .iter()
+ .flat_map(|response_model| {
+ let entities = self
+ .entities
+ .iter()
+ .filter(|entity| response_model.entity_identifiers.contains(&entity.identifier))
+ .map(|entity| entity.clone())
+ .collect::<Vec<_>>();
+
+ if entities.len() != response_model.entity_identifiers.len() {
+ return None;
+ }
+
+ let model = Model {
+ identifier: response_model.identifier.clone(),
+ entities: entities,
+ specializations: response_model.specializations.clone(),
+ number_of_parameters: response_model.number_of_parameters.clone(),
+ quantization: response_model.quantization.clone(),
+ accessibility: response_model.accessibility.clone(),
+ };
+ return Some(model);
+ })
+ .collect::<Vec<_>>();
+
+ if models.len() != self.models.len() {
+ return None;
+ }
+
+ return Some(models);
+ }
+}
diff --git a/crates/uzu/src/registry/mod.rs b/crates/uzu/src/registry/mod.rs
new file mode 100644
index 000000000..8f11c8419
--- /dev/null
+++ b/crates/uzu/src/registry/mod.rs
@@ -0,0 +1,11 @@
+mod cached;
+mod error;
+mod fixed;
+mod merged;
+pub mod mirai;
+pub mod openai;
+
+pub use cached::CachedRegistry;
+pub use error::Error;
+pub use fixed::FixedRegistry;
+pub use merged::MergedRegistry;
diff --git a/crates/uzu/src/registry/openai/config.rs b/crates/uzu/src/registry/openai/config.rs
new file mode 100644
index 000000000..d2c690ff4
--- /dev/null
+++ b/crates/uzu/src/registry/openai/config.rs
@@ -0,0 +1,85 @@
+use std::collections::HashMap;
+
+use serde::{Deserialize, Serialize};
+
+#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
+#[serde(rename_all = "snake_case")]
+pub struct Config {
+ pub identifier: String,
+ pub name: String,
+ pub api_endpoint: String,
+ pub api_key: Option<String>,
+ pub model_filter_pattern: Option<String>,
+ pub headers: Option<HashMap<String, String>>,
+}
+
+impl Config {
+ pub fn new(
+ identifier: String,
+ name: String,
+ api_endpoint: String,
+ api_key: Option<String>,
+ model_filter_pattern: Option<String>,
+ headers: Option<HashMap<String, String>>,
+ ) -> Self {
+ Self {
+ identifier,
+ name,
+ api_endpoint,
+ api_key,
+ model_filter_pattern,
+ headers,
+ }
+ }
+
+ pub fn openai(api_key: String) -> Self {
+ Self::new(
+ "openai".to_string(),
+ "OpenAI".to_string(),
+ "https://api.openai.com/v1".to_string(),
+ Some(api_key),
+ Some(r"^(?:gpt-\d[\d.]*[a-z]?|o\d+)(?:-(?:mini|nano|pro|turbo|codex(?:-mini|-max)?))*$".to_string()),
+ None,
+ )
+ }
+
+ pub fn ollama() -> Self {
+ Self::new("ollama".to_string(), "Ollama".to_string(), "http://localhost:11434/v1".to_string(), None, None, None)
+ }
+
+ pub fn baseten(api_key: String) -> Self {
+ Self::new(
+ "baseten".to_string(),
+ "Baseten".to_string(),
+ "https://inference.baseten.co/v1".to_string(),
+ Some(api_key),
+ None,
+ None,
+ )
+ }
+
+ pub fn anthropic(api_key: String) -> Self {
+ Self::new(
+ "anthropic".to_string(),
+ "Anthropic".to_string(),
+ "https://api.anthropic.com/v1/".to_string(),
+ Some(api_key.clone()),
+ Some(r"^claude-(?:opus|sonnet|haiku)-\d{1,2}(?:-\d{1,2})*$".to_string()),
+ Some(HashMap::from([
+ ("X-Api-Key".to_string(), api_key.clone()),
+ ("anthropic-version".to_string(), "2023-06-01".to_string()),
+ ])),
+ )
+ }
+
+ pub fn openrouter(api_key: String) -> Self {
+ Self::new(
+ "openrouter".to_string(),
+ "OpenRouter".to_string(),
+ "https://openrouter.ai/api/v1".to_string(),
+ Some(api_key.clone()),
+ None,
+ None,
+ )
+ }
+}
diff --git a/crates/uzu/src/registry/openai/mod.rs b/crates/uzu/src/registry/openai/mod.rs
new file mode 100644
index 000000000..fb357bb11
--- /dev/null
+++ b/crates/uzu/src/registry/openai/mod.rs
@@ -0,0 +1,125 @@
+mod config;
+
+use std::{future::Future, pin::Pin};
+
+pub use config::Config;
+use openai_api_rs::v1::api::OpenAIClient;
+use regex::Regex;
+use shoji::{
+ traits::Registry as RegistryTrait,
+ types::{Accessibility, Entity, EntityType, Model, Specialization},
+};
+
+use crate::registry::Error;
+
+pub struct Registry {
+ config: Config,
+ client: OpenAIClient,
+ model_filter: Option<Regex>,
+}
+
+impl Registry {
+ pub fn new(config: Config) -> Result<Self, Error> {
+ let mut client_builder = OpenAIClient::builder().with_endpoint(config.api_endpoint.clone());
+ if let Some(api_key) = config.api_key.clone() {
+ client_builder = client_builder.with_api_key(api_key);
+ }
+ if let Some(headers) = config.headers.clone() {
+ for (key, value) in headers.iter() {
+ client_builder = client_builder.with_header(key, value);
+ }
+ }
+
+ let client = client_builder.build().map_err(|error| Error::UnableToCreate {
+ message: error.to_string(),
+ })?;
+
+ let model_filter = config.model_filter_pattern.as_deref().map(Regex::new).transpose().map_err(|error| {
+ Error::UnableToCreate {
+ message: error.to_string(),
+ }
+ })?;
+
+ Ok(Self {
+ config,
+ client,
+ model_filter,
+ })
+ }
+}
+
+impl RegistryTrait for Registry {
+ type Error = Error;
+
+ fn indentifier(&self) -> String {
+ self.config.identifier.clone()
+ }
+
+ fn models(&self) -> Pin<Box<dyn Future<Output = Result<Vec<Model>, Error>> + Send + '_>> {
+ Box::pin(async {
+ let response = self.client.list_models().await.map_err(|error| Error::UnableToGetModels {
+ message: error.to_string(),
+ })?;
+ let mut identifiers =
+ response.inner.data.into_iter().filter_map(|model| model.id.clone()).collect::<Vec<_>>();
+ identifiers.sort();
+
+ let registry_entity = self.create_entity(EntityType::Registry);
+ let backend_entity = self.create_entity(EntityType::Backend);
+ let vendor_entity = self.create_entity(EntityType::Vendor);
+ let family_entity = self.create_entity(EntityType::Family);
+
+ let models = identifiers
+ .into_iter()
+ .filter(|identifier| self.model_filter.as_ref().is_none_or(|regex| regex.is_match(identifier)))
+ .map(|identifier| {
+ let variant_entity = Entity {
+ r#type: EntityType::Variant,
+ identifier: identifier.clone(),
+ parent_identifier: None,
+ name: identifier.clone(),
+ description: None,
+ version: None,
+ icons: vec![],
+ };
+ let model = Model {
+ identifier: identifier.clone(),
+ entities: vec![
+ registry_entity.clone(),
+ backend_entity.clone(),
+ vendor_entity.clone(),
+ family_entity.clone(),
+ variant_entity,
+ ],
+ specializations: vec![Specialization::Chat],
+ number_of_parameters: None,
+ quantization: None,
+ accessibility: Accessibility::Remote {
+ repository: None,
+ },
+ };
+ model
+ })
+ .collect();
+
+ Ok(models)
+ })
+ }
+}
+
+impl Registry {
+ fn create_entity(
+ &self,
+ r#type: EntityType,
+ ) -> Entity {
+ Entity {
+ r#type,
+ identifier: self.config.identifier.clone(),
+ parent_identifier: None,
+ name: self.config.name.clone(),
+ description: None,
+ version: None,
+ icons: vec![],
+ }
+ }
+}
diff --git a/crates/nagare/src/storage/config.rs b/crates/uzu/src/storage/config.rs
similarity index 88%
rename from crates/nagare/src/storage/config.rs
rename to crates/uzu/src/storage/config.rs
index ad69552bb..84b307da2 100644
--- a/crates/nagare/src/storage/config.rs
+++ b/crates/uzu/src/storage/config.rs
@@ -1,8 +1,9 @@
use std::path::PathBuf;
use serde::{Deserialize, Serialize};
+use shoji::types::Model;
-use crate::{device::Device, registry::types::Model};
+use crate::device::Device;
#[derive(Debug, Clone, PartialEq, Eq, Hash, Serialize, Deserialize)]
#[serde(rename_all = "snake_case")]
@@ -41,4 +42,8 @@ impl Config {
let checkpoint_version = model.checkpoint_version()?;
Some(self.cache_models_path().join(reference_type).join(model.cache_identifier()).join(checkpoint_version))
}
+
+ pub fn log_name(&self) -> String {
+ format!("{}.log", self.name)
+ }
}
diff --git a/crates/nagare/src/storage/error.rs b/crates/uzu/src/storage/error.rs
similarity index 100%
rename from crates/nagare/src/storage/error.rs
rename to crates/uzu/src/storage/error.rs
diff --git a/crates/nagare/src/storage/mod.rs b/crates/uzu/src/storage/mod.rs
similarity index 98%
rename from crates/nagare/src/storage/mod.rs
rename to crates/uzu/src/storage/mod.rs
index c9044b01a..aa3c87818 100644
--- a/crates/nagare/src/storage/mod.rs
+++ b/crates/uzu/src/storage/mod.rs
@@ -13,6 +13,7 @@ use download_manager::{
FileCheck, FileDownloadManager, FileDownloadManagerType, FileDownloadPhase, create_download_manager,
};
pub use error::Error;
+use shoji::types::{Accessibility, File, Model, Reference};
use tokio::{
runtime::Handle,
sync::broadcast::{Sender, channel},
@@ -21,7 +22,6 @@ use tokio_stream::wrappers::BroadcastStream;
use crate::{
helpers::SharedAccess,
- registry::types::{Accessibility, File, Model, Reference},
storage::types::{DownloadPhase, DownloadState, Item},
};
@@ -112,7 +112,7 @@ impl Storage {
}
let files = self.resolve_model_files(&model)?;
- let total_bytes: u64 = files.iter().map(|file| file.size).sum();
+ let total_bytes: u64 = files.iter().map(|file| file.size as u64).sum();
let cache_path = self.config.cache_model_path(&model).ok_or(Error::UnsupportedItem {
identifier: identifier.clone(),
@@ -134,7 +134,7 @@ impl Storage {
})?);
let file_task = download_manager
- .file_download_task(&file.url, &file_path, file_check, Some(file.size))
+ .file_download_task(&file.url, &file_path, file_check, Some(file.size as u64))
.await
.map_err(|error| Error::DownloadManager {
message: error.to_string(),
diff --git a/crates/nagare/src/storage/types/crc_snapshot.rs b/crates/uzu/src/storage/types/crc_snapshot.rs
similarity index 100%
rename from crates/nagare/src/storage/types/crc_snapshot.rs
rename to crates/uzu/src/storage/types/crc_snapshot.rs
diff --git a/crates/nagare/src/storage/types/download_phase.rs b/crates/uzu/src/storage/types/download_phase.rs
similarity index 100%
rename from crates/nagare/src/storage/types/download_phase.rs
rename to crates/uzu/src/storage/types/download_phase.rs
diff --git a/crates/nagare/src/storage/types/download_state.rs b/crates/uzu/src/storage/types/download_state.rs
similarity index 100%
rename from crates/nagare/src/storage/types/download_state.rs
rename to crates/uzu/src/storage/types/download_state.rs
diff --git a/crates/nagare/src/storage/types/item.rs b/crates/uzu/src/storage/types/item.rs
similarity index 98%
rename from crates/nagare/src/storage/types/item.rs
rename to crates/uzu/src/storage/types/item.rs
index 3322999d6..86abf1252 100644
--- a/crates/nagare/src/storage/types/item.rs
+++ b/crates/uzu/src/storage/types/item.rs
@@ -6,6 +6,7 @@ use std::{
use download_manager::{FileDownloadManager, FileDownloadState, FileDownloadTask};
use futures_util::future::join_all;
+use shoji::types::File;
use tokio::{
runtime::Handle,
sync::broadcast::{Sender, channel},
@@ -15,7 +16,6 @@ use tokio_stream::wrappers::BroadcastStream;
use crate::{
helpers::SharedAccess,
- registry::types::File,
storage::{
Error,
types::{CrcSnapshot, DownloadPhase, DownloadState, reduce_file_download_states},
@@ -113,7 +113,7 @@ impl Item {
if state.total_bytes == 0 {
if let Some(file_info) = self.files.get(i) {
if file_info.size > 0 {
- state.total_bytes = file_info.size;
+ state.total_bytes = file_info.size as u64;
}
}
}
@@ -145,7 +145,7 @@ impl Item {
if state.total_bytes == 0 {
if let Some(file_info) = self.files.get(i) {
if file_info.size > 0 {
- state.total_bytes = file_info.size;
+ state.total_bytes = file_info.size as u64;
}
}
}
@@ -268,7 +268,7 @@ impl Item {
let file_task = self
.file_download_manager
- .file_download_task(&file_info.url, &file_path, file_check, Some(file_info.size))
+ .file_download_task(&file_info.url, &file_path, file_check, Some(file_info.size as u64))
.await
.map_err(|error| Error::DownloadManager {
message: error.to_string(),
@@ -395,7 +395,7 @@ impl Item {
let _ = remove_dir_all(&self.cache_path);
}
- let total_bytes: u64 = self.files.iter().map(|f| f.size).sum();
+ let total_bytes: u64 = self.files.iter().map(|f| f.size as u64).sum();
let not_downloaded_state = DownloadState::not_downloaded(total_bytes);
self.update_state_and_broadcast(not_downloaded_state).await;
Ok(())
@@ -514,7 +514,7 @@ impl Item {
if state.total_bytes == 0 {
if let Some(file_info) = self.files.get(idx) {
if file_info.size > 0 {
- state.total_bytes = file_info.size;
+ state.total_bytes = file_info.size as u64;
}
}
}
@@ -597,7 +597,7 @@ impl Item {
if s.total_bytes == 0 {
if let Some(file_info) = model.files.get(i) {
if file_info.size > 0 {
- s.total_bytes = file_info.size;
+ s.total_bytes = file_info.size as u64;
}
}
}
diff --git a/crates/nagare/src/storage/types/mod.rs b/crates/uzu/src/storage/types/mod.rs
similarity index 100%
rename from crates/nagare/src/storage/types/mod.rs
rename to crates/uzu/src/storage/types/mod.rs
diff --git a/crates/nagare/tests/.gitignore b/crates/uzu/tests/.gitignore
similarity index 100%
rename from crates/nagare/tests/.gitignore
rename to crates/uzu/tests/.gitignore
diff --git a/crates/nagare/tests/common/mod.rs b/crates/uzu/tests/common/mod.rs
similarity index 100%
rename from crates/nagare/tests/common/mod.rs
rename to crates/uzu/tests/common/mod.rs
diff --git a/crates/nagare/tests/common/test_helpers.rs b/crates/uzu/tests/common/test_helpers.rs
similarity index 79%
rename from crates/nagare/tests/common/test_helpers.rs
rename to crates/uzu/tests/common/test_helpers.rs
index 91606f06b..c52ea5727 100644
--- a/crates/nagare/tests/common/test_helpers.rs
+++ b/crates/uzu/tests/common/test_helpers.rs
@@ -2,15 +2,13 @@
use std::path::PathBuf;
-use nagare::{
+use shoji::types::{Accessibility, Entity, EntityType, File, Hash, HashMethod, Model, Reference};
+use tokio::runtime::Handle;
+use uzu::{
device::Device,
- registry::{
- FixedRegistry,
- types::{Accessibility, Entity, EntityType, File, Hash, HashMethod, Model, Reference},
- },
+ registry::FixedRegistry,
storage::{Config, Storage},
};
-use tokio::runtime::Handle;
pub struct TestStorage {
pub models: Vec<Model>,
@@ -51,28 +49,54 @@ impl TestStorage {
}
fn test_model(index: usize) -> Model {
+ let registry_entity = Entity {
+ r#type: EntityType::Registry,
+ identifier: "test-registry".to_string(),
+ parent_identifier: None,
+ version: None,
+ name: "Test Registry".to_string(),
+ description: None,
+ icons: vec![],
+ };
+
+ let backend_entity = Entity {
+ r#type: EntityType::Backend,
+ identifier: "test-backend".to_string(),
+ parent_identifier: None,
+ version: None,
+ name: "Test Backend".to_string(),
+ description: None,
+ icons: vec![],
+ };
+
let vendor_entity = Entity {
r#type: EntityType::Vendor,
identifier: "test-vendor".to_string(),
+ parent_identifier: None,
+ version: None,
name: "Test Vendor".to_string(),
description: None,
- icon: vec![],
+ icons: vec![],
};
let family_entity = Entity {
r#type: EntityType::Family,
identifier: "test-family".to_string(),
+ parent_identifier: None,
+ version: None,
name: "Test Family".to_string(),
description: None,
- icon: vec![],
+ icons: vec![],
};
let model_entity = Entity {
- r#type: EntityType::Model,
+ r#type: EntityType::Variant,
identifier: format!("test-model-{}", index),
+ parent_identifier: None,
+ version: None,
name: format!("Test Model {}", index),
description: None,
- icon: vec![],
+ icons: vec![],
};
let files_1 = vec![
@@ -136,11 +160,12 @@ fn test_model(index: usize) -> Model {
];
Model {
- entities: vec![vendor_entity, family_entity, model_entity],
+ identifier: format!("test-model-{}", index),
+ entities: vec![registry_entity, backend_entity, vendor_entity, family_entity, model_entity],
specializations: vec![],
number_of_parameters: None,
+ quantization: None,
accessibility: Accessibility::Local {
- provider_identifier: "test".to_string(),
reference: Reference::Mirai {
toolchain_version: "1.0".to_string(),
repository: None,
diff --git a/crates/nagare/tests/common/tracing_setup.rs b/crates/uzu/tests/common/tracing_setup.rs
similarity index 100%
rename from crates/nagare/tests/common/tracing_setup.rs
rename to crates/uzu/tests/common/tracing_setup.rs
diff --git a/crates/uzu/tests/test_engine.rs b/crates/uzu/tests/test_engine.rs
index 6a0454669..74b78a64b 100644
--- a/crates/uzu/tests/test_engine.rs
+++ b/crates/uzu/tests/test_engine.rs
@@ -1,7 +1,7 @@
-#[cfg(not(target_family = "wasm"))]
+#![cfg(not(target_family = "wasm"))]
+
use uzu::engine::{Config, Engine};
-#[cfg(not(target_family = "wasm"))]
#[tokio::test]
async fn test_engine() {
dotenvy::dotenv().ok();
@@ -12,7 +12,8 @@ async fn test_engine() {
let models = engine.models().await.unwrap();
for model in models {
let identifier = model.identifier();
- let download_state = engine.downloader(&model).state().await.unwrap();
- println!("{}: {:?}", identifier, download_state.phase);
+ let registry_identifier = model.registry_entity().map(|entity| entity.identifier);
+ let download_phase = engine.downloader(&model).state().await.map_or(None, |state| Some(state.phase));
+ println!("{:?}, {}, {:?}", registry_identifier, identifier, download_phase);
}
}
diff --git a/crates/nagare/tests/test_storage_comprehensive_download.rs b/crates/uzu/tests/test_storage_comprehensive_download.rs
similarity index 99%
rename from crates/nagare/tests/test_storage_comprehensive_download.rs
rename to crates/uzu/tests/test_storage_comprehensive_download.rs
index 79191b035..a1f715e81 100644
--- a/crates/nagare/tests/test_storage_comprehensive_download.rs
+++ b/crates/uzu/tests/test_storage_comprehensive_download.rs
@@ -1,3 +1,5 @@
+#![cfg(not(target_family = "wasm"))]
+
mod common;
use std::time::Duration;
@@ -5,7 +7,7 @@ use std::time::Duration;
use common::test_helpers::TestStorage;
use futures_util::StreamExt;
use indicatif::{ProgressBar, ProgressStyle};
-use nagare::storage::types::{DownloadPhase, Item};
+use uzu::storage::types::{DownloadPhase, Item};
#[tokio::test(flavor = "multi_thread")]
async fn test_storage_comprehensive_download() -> Result<(), Box<dyn std::error::Error>> {
diff --git a/crates/nagare/tests/test_storage_comprehensive_state.rs b/crates/uzu/tests/test_storage_comprehensive_state.rs
similarity index 99%
rename from crates/nagare/tests/test_storage_comprehensive_state.rs
rename to crates/uzu/tests/test_storage_comprehensive_state.rs
index ba59bdcf9..7d7c2d2d3 100644
--- a/crates/nagare/tests/test_storage_comprehensive_state.rs
+++ b/crates/uzu/tests/test_storage_comprehensive_state.rs
@@ -7,7 +7,7 @@ use std::time::Duration;
use common::test_helpers::TestStorage;
use futures_util::StreamExt;
use indicatif::{ProgressBar, ProgressStyle};
-use nagare::storage::types::DownloadPhase;
+use uzu::storage::types::DownloadPhase;
#[tokio::test(flavor = "multi_thread")]
async fn test_storage_comprehensive_state_fresh_download_to_completion() -> Result<(), Box<dyn std::error::Error>> {
@@ -66,6 +66,7 @@ async fn test_storage_comprehensive_state_fresh_download_to_completion() -> Resu
Ok(())
}
+#[ignore]
#[tokio::test(flavor = "multi_thread")]
async fn test_storage_comprehensive_state_pause_and_resume() -> Result<(), Box<dyn std::error::Error>> {
let temp_dir = tempfile::tempdir()?;
diff --git a/crates/nagare/tests/test_storage_concurrent_multi_model.rs b/crates/uzu/tests/test_storage_concurrent_multi_model.rs
similarity index 99%
rename from crates/nagare/tests/test_storage_concurrent_multi_model.rs
rename to crates/uzu/tests/test_storage_concurrent_multi_model.rs
index 26590e2cb..ac93af035 100644
--- a/crates/nagare/tests/test_storage_concurrent_multi_model.rs
+++ b/crates/uzu/tests/test_storage_concurrent_multi_model.rs
@@ -1,10 +1,12 @@
+#![cfg(not(target_family = "wasm"))]
+
mod common;
use std::time::Duration;
use common::test_helpers::TestStorage;
use futures_util::StreamExt;
-use nagare::storage::types::DownloadPhase;
+use uzu::storage::types::DownloadPhase;
const TEST_COUNT: usize = 2;
diff --git a/crates/nagare/tests/test_storage_debug_file_preservation.rs b/crates/uzu/tests/test_storage_debug_file_preservation.rs
similarity index 99%
rename from crates/nagare/tests/test_storage_debug_file_preservation.rs
rename to crates/uzu/tests/test_storage_debug_file_preservation.rs
index 09c42dc14..aade71ae5 100644
--- a/crates/nagare/tests/test_storage_debug_file_preservation.rs
+++ b/crates/uzu/tests/test_storage_debug_file_preservation.rs
@@ -1,8 +1,9 @@
-#[cfg(target_vendor = "apple")]
+#![cfg(target_vendor = "apple")]
+
mod common;
use common::test_helpers::TestStorage;
-use nagare::storage::types::DownloadPhase;
+use uzu::storage::types::DownloadPhase;
#[ignore]
#[tokio::test(flavor = "multi_thread")]
diff --git a/crates/nagare/tests/test_storage_stall_detection.rs b/crates/uzu/tests/test_storage_stall_detection.rs
similarity index 98%
rename from crates/nagare/tests/test_storage_stall_detection.rs
rename to crates/uzu/tests/test_storage_stall_detection.rs
index 9c488f5bb..54772a941 100644
--- a/crates/nagare/tests/test_storage_stall_detection.rs
+++ b/crates/uzu/tests/test_storage_stall_detection.rs
@@ -1,10 +1,12 @@
+#![cfg(not(target_family = "wasm"))]
+
mod common;
use std::time::Duration;
use common::test_helpers::TestStorage;
use futures_util::StreamExt;
-use nagare::storage::types::DownloadPhase;
+use uzu::storage::types::DownloadPhase;
#[tokio::test(flavor = "multi_thread")]
async fn test_stall_detection_no_progress() -> Result<(), Box<dyn std::error::Error>> {