Skip to content

armgit / uzu

Public Imported from GitHub
0

A high-performance inference engine for AI models

Put the test_engine back (#395)

eugene1fcdbc136088
diff --git a/bindings/python/uzu/__init__.pyi b/bindings/python/uzu/__init__.pyi
index c101468c7..e924fd6a8 100644
--- a/bindings/python/uzu/__init__.pyi
+++ b/bindings/python/uzu/__init__.pyi
@@ -34,6 +34,7 @@ __all__ = [
"CliApplication",
"ContextLength",
"Device",
+ "DownloadManagerType",
"DownloadPhase",
"DownloadState",
"Downloader",
@@ -683,7 +684,9 @@ class EngineConfig:
def allow_ollama_usage(self) -> builtins.bool: ...
@property
def allow_lmstudio_usage(self) -> builtins.bool: ...
- def __new__(cls, application_identifier: typing.Optional[builtins.str], mirai_api_key: typing.Optional[builtins.str], lalamo_path: typing.Optional[builtins.str], huggingface_api_key: typing.Optional[builtins.str], openai_api_key: typing.Optional[builtins.str], anthropic_api_key: typing.Optional[builtins.str], gemini_api_key: typing.Optional[builtins.str], xai_api_key: typing.Optional[builtins.str], baseten_api_key: typing.Optional[builtins.str], openrouter_api_key: typing.Optional[builtins.str], allow_ollama_usage: builtins.bool, allow_lmstudio_usage: builtins.bool) -> EngineConfig: ...
+ @property
+ def download_manager_type(self) -> DownloadManagerType: ...
+ def __new__(cls, application_identifier: typing.Optional[builtins.str], mirai_api_key: typing.Optional[builtins.str], lalamo_path: typing.Optional[builtins.str], huggingface_api_key: typing.Optional[builtins.str], openai_api_key: typing.Optional[builtins.str], anthropic_api_key: typing.Optional[builtins.str], gemini_api_key: typing.Optional[builtins.str], xai_api_key: typing.Optional[builtins.str], baseten_api_key: typing.Optional[builtins.str], openrouter_api_key: typing.Optional[builtins.str], allow_ollama_usage: builtins.bool, allow_lmstudio_usage: builtins.bool, download_manager_type: DownloadManagerType) -> EngineConfig: ...
@staticmethod
def create() -> EngineConfig: ...
def with_application_identifier(self, application_identifier: builtins.str) -> EngineConfig: ...
@@ -698,6 +701,7 @@ class EngineConfig:
def with_openrouter_api_key(self, openrouter_api_key: builtins.str) -> EngineConfig: ...
def with_allow_ollama_usage(self, allow_ollama_usage: builtins.bool) -> EngineConfig: ...
def with_allow_lmstudio_usage(self, allow_lmstudio_usage: builtins.bool) -> EngineConfig: ...
+ def with_download_manager_type(self, download_manager_type: DownloadManagerType) -> EngineConfig: ...
@typing.final
class Feature:
@@ -1252,6 +1256,11 @@ class ClassificationSessionState(enum.Enum):
Idle = ...
Classifying = ...
+class DownloadManagerType(enum.Enum):
+ Native = ...
+ Universal = ...
+
@typing.final
class HashMethod(enum.Enum):
CRC32C = ...
diff --git a/bindings/swift/Sources/Uzu/Generated/uzu/uzu.swift b/bindings/swift/Sources/Uzu/Generated/uzu/uzu.swift
index edd3b4975..da479786f 100644
--- a/bindings/swift/Sources/Uzu/Generated/uzu/uzu.swift
+++ b/bindings/swift/Sources/Uzu/Generated/uzu/uzu.swift
@@ -2258,10 +2258,11 @@ public struct EngineConfig: Equatable, Hashable, Codable {
public var openrouterApiKey: String?
public var allowOllamaUsage: Bool
public var allowLmstudioUsage: Bool
+ public var downloadManagerType: DownloadManagerType
// Default memberwise initializers are never public by default, so we
// declare one manually.
- public init(applicationIdentifier: String?, miraiApiKey: String?, lalamoPath: String?, huggingfaceApiKey: String?, openaiApiKey: String?, anthropicApiKey: String?, geminiApiKey: String?, xaiApiKey: String?, basetenApiKey: String?, openrouterApiKey: String?, allowOllamaUsage: Bool, allowLmstudioUsage: Bool) {
+ public init(applicationIdentifier: String?, miraiApiKey: String?, lalamoPath: String?, huggingfaceApiKey: String?, openaiApiKey: String?, anthropicApiKey: String?, geminiApiKey: String?, xaiApiKey: String?, basetenApiKey: String?, openrouterApiKey: String?, allowOllamaUsage: Bool, allowLmstudioUsage: Bool, downloadManagerType: DownloadManagerType) {
self.applicationIdentifier = applicationIdentifier
self.miraiApiKey = miraiApiKey
self.lalamoPath = lalamoPath
@@ -2274,6 +2275,7 @@ public struct EngineConfig: Equatable, Hashable, Codable {
self.openrouterApiKey = openrouterApiKey
self.allowOllamaUsage = allowOllamaUsage
self.allowLmstudioUsage = allowLmstudioUsage
+ self.downloadManagerType = downloadManagerType
}
@@ -2322,6 +2324,15 @@ public func withBasetenApiKey(basetenApiKey: String) -> EngineConfig {
})
}
+public func withDownloadManagerType(downloadManagerType: DownloadManagerType) -> EngineConfig {
+ return try! FfiConverterTypeEngineConfig_lift(try! rustCall() {
+ uniffi_uzu_fn_method_engineconfig_with_download_manager_type(
+ FfiConverterTypeEngineConfig_lower(self),
+ FfiConverterTypeDownloadManagerType_lower(downloadManagerType),$0
+ )
+})
+}
+
public func withGeminiApiKey(geminiApiKey: String) -> EngineConfig {
return try! FfiConverterTypeEngineConfig_lift(try! rustCall() {
uniffi_uzu_fn_method_engineconfig_with_gemini_api_key(
@@ -2411,7 +2422,8 @@ public struct FfiConverterTypeEngineConfig: FfiConverterRustBuffer {
basetenApiKey: FfiConverterOptionString.read(from: &buf),
openrouterApiKey: FfiConverterOptionString.read(from: &buf),
allowOllamaUsage: FfiConverterBool.read(from: &buf),
- allowLmstudioUsage: FfiConverterBool.read(from: &buf)
+ allowLmstudioUsage: FfiConverterBool.read(from: &buf),
+ downloadManagerType: FfiConverterTypeDownloadManagerType.read(from: &buf)
)
}
@@ -2428,6 +2440,7 @@ public struct FfiConverterTypeEngineConfig: FfiConverterRustBuffer {
FfiConverterOptionString.write(value.openrouterApiKey, into: &buf)
FfiConverterBool.write(value.allowOllamaUsage, into: &buf)
FfiConverterBool.write(value.allowLmstudioUsage, into: &buf)
+ FfiConverterTypeDownloadManagerType.write(value.downloadManagerType, into: &buf)
}
}
@@ -2610,6 +2623,73 @@ public func FfiConverterTypeDeviceError_lower(_ value: DeviceError) -> RustBuffe
return FfiConverterTypeDeviceError.lower(value)
}
+// Note that we don't yet support `indirect` for enums.
+// See https://github.com/mozilla/uniffi-rs/issues/396 for further discussion.
+
+public enum DownloadManagerType: Equatable, Hashable, Codable {
+
+ case native
+ case universal
+
+
+
+
+
+}
+
+#if compiler(>=6)
+extension DownloadManagerType: Sendable {}
+#endif
+
+#if swift(>=5.8)
+@_documentation(visibility: private)
+#endif
+public struct FfiConverterTypeDownloadManagerType: FfiConverterRustBuffer {
+ typealias SwiftType = DownloadManagerType
+
+ public static func read(from buf: inout (data: Data, offset: Data.Index)) throws -> DownloadManagerType {
+ let variant: Int32 = try readInt(&buf)
+ switch variant {
+
+ case 1: return .native
+
+ case 2: return .universal
+
+ default: throw UniffiInternalError.unexpectedEnumCase
+ }
+ }
+
+ public static func write(_ value: DownloadManagerType, into buf: inout [UInt8]) {
+ switch value {
+
+
+ case .native:
+ writeInt(&buf, Int32(1))
+
+
+ case .universal:
+ writeInt(&buf, Int32(2))
+
+ }
+ }
+}
+
+
+#if swift(>=5.8)
+@_documentation(visibility: private)
+#endif
+public func FfiConverterTypeDownloadManagerType_lift(_ buf: RustBuffer) throws -> DownloadManagerType {
+ return try FfiConverterTypeDownloadManagerType.lift(buf)
+}
+
+#if swift(>=5.8)
+@_documentation(visibility: private)
+#endif
+public func FfiConverterTypeDownloadManagerType_lower(_ value: DownloadManagerType) -> RustBuffer {
+ return FfiConverterTypeDownloadManagerType.lower(value)
+}
+
+
// Note that we don't yet support `indirect` for enums.
// See https://github.com/mozilla/uniffi-rs/issues/396 for further discussion.
diff --git a/bindings/typescript/src/napi/index.d.ts b/bindings/typescript/src/napi/index.d.ts
index f20314157..770f2662d 100644
--- a/bindings/typescript/src/napi/index.d.ts
+++ b/bindings/typescript/src/napi/index.d.ts
@@ -924,7 +924,8 @@ export declare class EngineConfig {
openrouterApiKey?: string
allowOllamaUsage: boolean
allowLmstudioUsage: boolean
- constructor(applicationIdentifier?: string, miraiApiKey?: string, lalamoPath?: string, huggingfaceApiKey?: string, openaiApiKey?: string, anthropicApiKey?: string, geminiApiKey?: string, xaiApiKey?: string, basetenApiKey?: string, openrouterApiKey?: string, allowOllamaUsage: boolean, allowLmstudioUsage: boolean)
+ downloadManagerType: DownloadManagerType
+ constructor(applicationIdentifier?: string, miraiApiKey?: string, lalamoPath?: string, huggingfaceApiKey?: string, openaiApiKey?: string, anthropicApiKey?: string, geminiApiKey?: string, xaiApiKey?: string, basetenApiKey?: string, openrouterApiKey?: string, allowOllamaUsage: boolean, allowLmstudioUsage: boolean, downloadManagerType: DownloadManagerType)
static create(): EngineConfig
withApplicationIdentifier(applicationIdentifier: string): EngineConfig
@@ -939,6 +940,7 @@ export declare class EngineConfig {
withOpenrouterApiKey(openrouterApiKey: string): EngineConfig
withAllowOllamaUsage(allowOllamaUsage: boolean): EngineConfig
withAllowLmstudioUsage(allowLmstudioUsage: boolean): EngineConfig
+ withDownloadManagerType(downloadManagerType: DownloadManagerType): EngineConfig
}
export declare class Player {
@@ -961,6 +963,11 @@ export type CliError =
export type DeviceError =
| { type: 'UnsupportedDevice' }
+export declare const enum DownloadManagerType {
+ Native = 'Native',
+ Universal = 'Universal'
+}
+
export type DownloadPhase =
DownloadPhaseNotDownloaded | DownloadPhaseDownloading | DownloadPhasePaused | DownloadPhaseDownloaded | DownloadPhaseLocked | DownloadPhaseError
diff --git a/bindings/typescript/src/napi/index.js b/bindings/typescript/src/napi/index.js
index c734311a2..39871c6aa 100644
--- a/bindings/typescript/src/napi/index.js
+++ b/bindings/typescript/src/napi/index.js
@@ -627,4 +627,5 @@ module.exports.EngineCallback = nativeBinding.EngineCallback
module.exports.EngineConfig = nativeBinding.EngineConfig
module.exports.Player = nativeBinding.Player
module.exports.Settings = nativeBinding.Settings
+module.exports.DownloadManagerType = nativeBinding.DownloadManagerType
module.exports.SettingKind = nativeBinding.SettingKind
diff --git a/bindings/typescript/src/napi/index.mjs b/bindings/typescript/src/napi/index.mjs
index 0f802afd0..0b42505e5 100644
--- a/bindings/typescript/src/napi/index.mjs
+++ b/bindings/typescript/src/napi/index.mjs
@@ -124,4 +124,5 @@ export const EngineCallback = cjs.EngineCallback;
export const EngineConfig = cjs.EngineConfig;
export const Player = cjs.Player;
export const Settings = cjs.Settings;
+export const DownloadManagerType = cjs.DownloadManagerType;
export const SettingKind = cjs.SettingKind;
diff --git a/crates/cli-storage/src/main.rs b/crates/cli-storage/src/main.rs
index 47a48bb61..70ccde174 100644
--- a/crates/cli-storage/src/main.rs
+++ b/crates/cli-storage/src/main.rs
@@ -13,9 +13,8 @@ use crossterm::{
execute,
terminal::{EnterAlternateScreen, LeaveAlternateScreen, disable_raw_mode, enable_raw_mode},
};
-use download_manager::FileDownloadManagerType;
use ratatui::{Terminal, backend::CrosstermBackend};
-use uzu::engine::{Engine, EngineConfig};
+use uzu::engine::{DownloadManagerType, Engine, EngineConfig};
use crate::{app::App, events::EventHandler};
@@ -27,29 +26,29 @@ struct Cli {
#[derive(Debug, Clone, Copy, ValueEnum)]
enum DownloadManagerCliType {
- Apple,
+ Native,
Universal,
}
impl Default for DownloadManagerCliType {
fn default() -> Self {
- FileDownloadManagerType::default().into()
+ DownloadManagerType::default().into()
}
}
-impl From<FileDownloadManagerType> for DownloadManagerCliType {
- fn from(download_manager_type: FileDownloadManagerType) -> Self {
+impl From<DownloadManagerType> for DownloadManagerCliType {
+ fn from(download_manager_type: DownloadManagerType) -> Self {
match download_manager_type {
- FileDownloadManagerType::Apple => Self::Apple,
- FileDownloadManagerType::Universal => Self::Universal,
+ DownloadManagerType::Native => Self::Native,
+ DownloadManagerType::Universal => Self::Universal,
}
}
}
-impl From<DownloadManagerCliType> for FileDownloadManagerType {
+impl From<DownloadManagerCliType> for DownloadManagerType {
fn from(download_manager_type: DownloadManagerCliType) -> Self {
match download_manager_type {
- DownloadManagerCliType::Apple => Self::Apple,
+ DownloadManagerCliType::Native => Self::Native,
DownloadManagerCliType::Universal => Self::Universal,
}
}
@@ -60,8 +59,8 @@ async fn main() -> Result<(), Box<dyn std::error::Error>> {
let cli = Cli::parse();
dotenvy::dotenv().ok();
let runtime = tokio::runtime::Handle::current();
- let engine =
- Arc::new(Engine::new_with_download_manager_type(EngineConfig::default(), cli.download_manager.into()).await?);
+ let config = EngineConfig::default().with_download_manager_type(cli.download_manager.into());
+ let engine = Arc::new(Engine::new(config).await?);
// Setup terminal
enable_raw_mode()?;
diff --git a/crates/download-manager/src/download_error.rs b/crates/download-manager/src/download_error.rs
index fd5d8b640..169ce3a23 100644
--- a/crates/download-manager/src/download_error.rs
+++ b/crates/download-manager/src/download_error.rs
@@ -10,8 +10,6 @@ pub enum DownloadError {
Canceled,
#[error("resume unsupported")]
ResumeUnsupported,
- #[error("unsupported file download manager type")]
- UnsupportedType,
#[error("bad url")]
BadUrl,
#[error("missing download info for task")]
diff --git a/crates/download-manager/src/file_download_manager.rs b/crates/download-manager/src/file_download_manager.rs
index 4417526ca..10a7d0fe5 100644
--- a/crates/download-manager/src/file_download_manager.rs
+++ b/crates/download-manager/src/file_download_manager.rs
@@ -16,16 +16,16 @@ pub type SharedDownloadEventSender = Arc<DownloadEventSender>;
#[serde(rename_all = "snake_case")]
pub enum FileDownloadManagerType {
Universal,
+ #[cfg(target_vendor = "apple")]
Apple,
}
impl Default for FileDownloadManagerType {
+ #[allow(unreachable_code)]
fn default() -> Self {
- if cfg!(target_vendor = "apple") {
- Self::Apple
- } else {
- Self::Universal
- }
+ #[cfg(target_vendor = "apple")]
+ return Self::Apple;
+ Self::Universal
}
}
@@ -69,17 +69,11 @@ impl dyn FileDownloadManager {
Box::new(UniversalDownloadManager::from_tokio_handle(tokio_handle)?);
Ok(manager)
},
+ #[cfg(target_vendor = "apple")]
FileDownloadManagerType::Apple => {
- #[cfg(target_vendor = "apple")]
- {
- let manager: Box<dyn FileDownloadManager> =
- Box::new(AppleDownloadManager::from_tokio_handle(tokio_handle)?);
- Ok(manager)
- }
- #[cfg(not(target_vendor = "apple"))]
- {
- Err(DownloadError::UnsupportedType)
- }
+ let manager: Box<dyn FileDownloadManager> =
+ Box::new(AppleDownloadManager::from_tokio_handle(tokio_handle)?);
+ Ok(manager)
},
}
}
diff --git a/crates/uzu/src/engine/config.rs b/crates/uzu/src/engine/config.rs
index 374fb3fc0..3991a027c 100644
--- a/crates/uzu/src/engine/config.rs
+++ b/crates/uzu/src/engine/config.rs
@@ -2,7 +2,10 @@ use std::env;
use serde::{Deserialize, Serialize};
-use crate::settings::{SettingKind, Settings, SettingsError};
+use crate::{
+ engine::DownloadManagerType,
+ settings::{SettingKind, Settings, SettingsError},
+};
pub const KEY_MIRAI_API_KEY: &str = "MIRAI_API_KEY";
pub const KEY_LALAMO_PATH: &str = "LALAMO_PATH";
@@ -30,6 +33,8 @@ pub struct EngineConfig {
pub openrouter_api_key: Option<String>,
pub allow_ollama_usage: bool,
pub allow_lmstudio_usage: bool,
+ #[serde(default)]
+ pub download_manager_type: DownloadManagerType,
}
impl Default for EngineConfig {
@@ -47,6 +52,7 @@ impl Default for EngineConfig {
openrouter_api_key: env::var(KEY_OPENROUTER_API_KEY).ok(),
allow_ollama_usage: true,
allow_lmstudio_usage: true,
+ download_manager_type: DownloadManagerType::default(),
}
}
}
@@ -219,4 +225,15 @@ impl EngineConfig {
..self.clone()
}
}
+
+ #[bindings::export(Method)]
+ pub fn with_download_manager_type(
+ &self,
+ download_manager_type: DownloadManagerType,
+ ) -> Self {
+ Self {
+ download_manager_type,
+ ..self.clone()
+ }
+ }
}
diff --git a/crates/uzu/src/engine/download_manager.rs b/crates/uzu/src/engine/download_manager.rs
new file mode 100644
index 000000000..beb91b546
--- /dev/null
+++ b/crates/uzu/src/engine/download_manager.rs
@@ -0,0 +1,30 @@
+use download_manager::FileDownloadManagerType;
+use serde::{Deserialize, Serialize};
+
+#[bindings::export(Enumeration)]
+#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Serialize, Deserialize)]
+#[serde(rename_all = "snake_case")]
+pub enum DownloadManagerType {
+ #[cfg(target_vendor = "apple")]
+ Native,
+ Universal,
+}
+
+impl Default for DownloadManagerType {
+ #[allow(unreachable_code)]
+ fn default() -> Self {
+ #[cfg(target_vendor = "apple")]
+ return Self::Native;
+ Self::Universal
+ }
+}
+
+impl From<DownloadManagerType> for FileDownloadManagerType {
+ fn from(value: DownloadManagerType) -> Self {
+ match value {
+ #[cfg(target_vendor = "apple")]
+ DownloadManagerType::Native => Self::Apple,
+ DownloadManagerType::Universal => Self::Universal,
+ }
+ }
+}
diff --git a/crates/uzu/src/engine/mod.rs b/crates/uzu/src/engine/mod.rs
index 92b6d75d2..a3549a7ab 100644
--- a/crates/uzu/src/engine/mod.rs
+++ b/crates/uzu/src/engine/mod.rs
@@ -1,15 +1,16 @@
mod callback;
pub mod config;
+mod download_manager;
mod downloader;
mod error;
-use std::{collections::HashMap, path::PathBuf, sync::Arc};
+use std::{collections::HashMap, sync::Arc};
use backend_remote::openai::Backend as OpenAIBackend;
use backend_uzu::inference::Backend as UzuBackend;
pub use callback::{EngineCallback, EngineCallbackType};
pub use config::EngineConfig;
-use download_manager::FileDownloadManagerType;
+pub use download_manager::DownloadManagerType;
pub use downloader::{Downloader, DownloaderStream, DownloaderStreamUpdate};
pub use error::EngineError;
use indexmap::IndexSet;
@@ -53,14 +54,36 @@ pub struct Engine {
impl Engine {
pub async fn new(config: EngineConfig) -> Result<Self, EngineError> {
- Self::new_with_download_manager_type(config, FileDownloadManagerType::default()).await
- }
+ let tokio_handle = Handle::try_current().map_err(|error| EngineError::TokioError {
+ message: error.to_string(),
+ })?;
+
+ let settings = if let Some(application_identifier) = &config.application_identifier {
+ Some(Settings::new(application_identifier.clone())?)
+ } else {
+ None
+ };
+ let mut config = config;
+ if let Some(settings) = &settings {
+ config.synchronize_with_settings(settings)?;
+ }
+
+ let device = Device::new()?;
+ let registry = SharedAccess::new(MergedRegistry::new(vec![]));
+ let storage_config = StorageConfig::new(device.clone(), None, "mirai".to_string())
+ .with_download_manager_type(config.download_manager_type.into());
+ logs::start(storage_config.cache_path(), &storage_config.log_name(), false);
- pub async fn new_with_download_manager_type(
- config: EngineConfig,
- download_manager_type: FileDownloadManagerType,
- ) -> Result<Self, EngineError> {
- let (engine, config, device) = Self::new_base(config, download_manager_type, None).await?;
+ let storage = SharedAccess::new(Storage::new(tokio_handle, storage_config).await?);
+
+ let engine = Self {
+ settings: SharedAccess::new(settings),
+ storage,
+ registry,
+ backends: SharedAccess::new(HashMap::new()),
+ callback: SharedAccess::new(None),
+ };
+ engine.spawn_storage_listener().await;
{
let uzu_backend = UzuBackend::new();
@@ -131,44 +154,6 @@ impl Engine {
Ok(engine)
}
-
- async fn new_base(
- config: EngineConfig,
- download_manager_type: FileDownloadManagerType,
- cache_path: Option<PathBuf>,
- ) -> Result<(Self, EngineConfig, Device), EngineError> {
- let tokio_handle = Handle::try_current().map_err(|error| EngineError::TokioError {
- message: error.to_string(),
- })?;
-
- let settings = if let Some(application_identifier) = &config.application_identifier {
- Some(Settings::new(application_identifier.clone())?)
- } else {
- None
- };
- let mut config = config;
- if let Some(settings) = &settings {
- config.synchronize_with_settings(settings)?;
- }
-
- let device = Device::new()?;
- let registry = SharedAccess::new(MergedRegistry::new(vec![]));
- let storage_config = StorageConfig::new(device.clone(), cache_path, "mirai".to_string())
- .with_download_manager_type(download_manager_type);
- logs::start(storage_config.cache_path(), &storage_config.log_name(), false);
-
- let storage = SharedAccess::new(Storage::new(tokio_handle, storage_config).await?);
-
- let engine = Self {
- settings: SharedAccess::new(settings),
- storage,
- registry,
- backends: SharedAccess::new(HashMap::new()),
- callback: SharedAccess::new(None),
- };
- engine.spawn_storage_listener().await;
- Ok((engine, config, device))
- }
}
#[bindings::export(Implementation)]
@@ -197,7 +182,7 @@ impl Engine {
registry: Box<dyn Registry<Error = RegistryError>>,
) -> Result<(), EngineError> {
self.registry.lock().await.add(Box::new(CachedRegistry::new(registry)))?;
- self.handle_registry_resfresh().await?;
+ self.handle_registry_refresh().await?;
Ok(())
}
@@ -217,7 +202,7 @@ impl Engine {
registry_identifier: String,
) -> Result<(), EngineError> {
self.registry.lock().await.remove(&registry_identifier)?;
- self.handle_registry_resfresh().await?;
+ self.handle_registry_refresh().await?;
Ok(())
}
@@ -358,7 +343,7 @@ impl Engine {
if let Some(model) = self.model_by_repo_id(identifier.clone()).await? {
return Ok(Some(model));
}
- self.model_by_path(identifier.clone()).await
+ self.model_by_path(identifier).await
}
#[bindings::export(Method)]
@@ -384,10 +369,8 @@ impl Engine {
) -> Result<Option<Model>, EngineError> {
let models = self.models().await?;
for model in models {
- if let Some(model_path) = self.model_path(&model).await {
- if model_path == path {
- return Ok(Some(model));
- }
+ if self.model_path(&model).await.is_some_and(|model_path| model_path == path) {
+ return Ok(Some(model));
}
}
Ok(None)
@@ -401,29 +384,26 @@ impl Engine {
&self,
model: &Model,
) -> Option<String> {
- let path = if model.is_local() {
- if let Some(local_external_path) = model.local_external_path() {
- Some(local_external_path.clone())
- } else {
- let storage = self.storage.lock().await;
- let state = storage.state(&model.identifier.clone()).await?;
- match state.phase {
- DownloadPhase::Downloaded {} => {
- storage.config.cache_model_path(model).map(|path| path.to_string_lossy().to_string())
- },
- DownloadPhase::NotDownloaded {}
- | DownloadPhase::Downloading {}
- | DownloadPhase::Paused {}
- | DownloadPhase::Locked {}
- | DownloadPhase::Error {
- ..
- } => None,
- }
- }
- } else {
- None
- };
- path
+ if !model.is_local() {
+ return None;
+ }
+ if let Some(local_external_path) = model.local_external_path() {
+ return Some(local_external_path);
+ }
+ let storage = self.storage.lock().await;
+ let state = storage.state(&model.identifier).await?;
+ match state.phase {
+ DownloadPhase::Downloaded {} => {
+ storage.config.cache_model_path(model).map(|path| path.to_string_lossy().to_string())
+ },
+ DownloadPhase::NotDownloaded {}
+ | DownloadPhase::Downloading {}
+ | DownloadPhase::Paused {}
+ | DownloadPhase::Locked {}
+ | DownloadPhase::Error {
+ ..
+ } => None,
+ }
}
#[bindings::export(Method)]
@@ -451,7 +431,7 @@ impl Engine {
return Ok(DownloaderStream::empty(model.identifier.clone()));
}
downloader.resume().await?;
- Ok(downloader.progress().await?)
+ downloader.progress().await
}
#[bindings::export(Method)]
@@ -524,7 +504,7 @@ impl Engine {
impl Engine {
#[bindings::export(Method)]
pub async fn settings(&self) -> Result<Settings, EngineError> {
- Ok(self.settings.lock().await.clone().ok_or(EngineError::SettingsNotAvailable)?)
+ self.settings.lock().await.clone().ok_or(EngineError::SettingsNotAvailable)
}
}
@@ -533,7 +513,7 @@ impl Engine {
self.storage.lock().await.subscribe()
}
- async fn handle_registry_resfresh(&self) -> Result<(), EngineError> {
+ async fn handle_registry_refresh(&self) -> Result<(), EngineError> {
let models = self.registry.lock().await.models().await?;
self.storage.lock().await.refresh(models).await?;
if let Some(callback) = self.callback.lock().await.as_ref().cloned() {
diff --git a/crates/uzu/tests/test_engine.rs b/crates/uzu/tests/test_engine.rs
new file mode 100644
index 000000000..1f6013680
--- /dev/null
+++ b/crates/uzu/tests/test_engine.rs
@@ -0,0 +1,131 @@
+#![cfg(not(target_family = "wasm"))]
+
+use uzu::{
+ engine::{Engine, EngineConfig},
+ session::chat::ChatSessionStreamChunk,
+ types::session::{
+ chat::{ChatConfig, ChatMessage, ChatReplyConfig},
+ classification::ClassificationMessage,
+ },
+};
+
+#[ignore]
+#[tokio::test]
+async fn test_engine_chat() {
+ dotenvy::dotenv().ok();
+
+ let config = EngineConfig::default();
+ let engine = Engine::new(config).await.unwrap();
+
+ println!("-------------------------");
+ let models = engine.models().await.unwrap();
+ for model in models {
+ let identifier = model.identifier.clone();
+ let name = model.name();
+ let repo_ids = model.repo_ids();
+ let registry_identifier = model.registry.identifier.clone();
+ let backend_identifiers = model.backends.iter().map(|backend| backend.identifier.clone()).collect::<Vec<_>>();
+ let family_vendor_identifier = model.family.as_ref().map(|family| family.vendor.identifier.clone());
+ let family_identifier = model.family.as_ref().map(|family| family.identifier.clone());
+ let properties_identifier = model.properties.as_ref().map(|properties| properties.identifier.clone());
+ let quantization_vendor_identifier =
+ model.quantization.as_ref().map(|quantization| quantization.vendor.identifier.clone());
+ let quantization_identifier = model.quantization.as_ref().map(|quantization| quantization.identifier.clone());
+ let download_phase = engine.downloader(&model).state().await.map_or(None, |state| Some(state.phase));
+ println!("identifier: {}", identifier);
+ println!("name: {}", name);
+ println!("repo_ids: {:?}", repo_ids);
+ println!("registry_identifier: {}", registry_identifier);
+ println!("backend_identifiers: {:?}", backend_identifiers);
+ println!("family_vendor_identifier: {:?}", family_vendor_identifier);
+ println!("family_identifier: {:?}", family_identifier);
+ println!("properties_identifier: {:?}", properties_identifier);
+ println!("quantization_vendor_identifier: {:?}", quantization_vendor_identifier);
+ println!("quantization_identifier: {:?}", quantization_identifier);
+ println!("download_phase: {:?}", download_phase);
+ println!("specializations: {:?}", model.specializations);
+ println!("-------------------------");
+ }
+
+ let model = engine.model("alibaba:qwen3:0.6b".to_string()).await.unwrap().unwrap();
+ while let Some(update) = engine.download(&model).await.unwrap().next().await {
+ println!("Downloading: {}", update.progress());
+ }
+
+ let session = engine.chat(model, ChatConfig::default()).await.unwrap();
+ session.reset().await.unwrap();
+
+ let messages = vec![
+ ChatMessage::system().with_text("You are a helpful assistant.".to_string()),
+ ChatMessage::user().with_text("My name is John Doe".to_string()),
+ ];
+ let stream = session.reply_with_stream(messages, ChatReplyConfig::default()).await;
+ while let Some(progress) = stream.next().await {
+ match progress {
+ ChatSessionStreamChunk::Replies {
+ replies,
+ } => {
+ let state = session.state().await;
+ let messages = session.messages().await;
+ let roles = messages.iter().map(|message| message.role.clone()).collect::<Vec<_>>();
+ println!("State: {state:?}");
+ println!("Roles: {roles:?}");
+ for reply in replies {
+ let duration = reply.stats.duration;
+ let finish_reason = reply.finish_reason;
+ let text_length = reply.message.text().unwrap_or_default().len();
+ println!(
+ "\tDuration: {duration}\n\tFinish reason: {finish_reason:?}\n\tText length: {text_length}"
+ );
+ }
+ },
+ ChatSessionStreamChunk::Error {
+ error,
+ } => eprintln!("Stream error: {error}"),
+ }
+ }
+
+ let messages = vec![ChatMessage::user().with_text("What is my name?".to_string())];
+ let _ = session.reply(messages, ChatReplyConfig::default()).await.unwrap();
+
+ let messages = session.messages().await;
+ for message in messages {
+ println!("Message: {message:?}");
+ }
+}
+
+#[ignore]
+#[tokio::test]
+async fn test_engine_classification() {
+ dotenvy::dotenv().ok();
+
+ let config = EngineConfig::default();
+ let engine = Engine::new(config).await.unwrap();
+ let model = engine.model("ModernBERT-Chat-Moderation".to_string()).await.unwrap().unwrap();
+ while let Some(update) = engine.download(&model).await.unwrap().next().await {
+ println!("Downloading: {}", update.progress());
+ }
+
+ let session = engine.classification(model).await.unwrap();
+ let messages = vec![ClassificationMessage::user("Hi!".to_string())];
+ let result = session.classify(messages).await.unwrap();
+ println!("Output: {result:?}");
+}
+
+#[ignore]
+#[tokio::test]
+async fn test_engine_text_to_speech() {
+ dotenvy::dotenv().ok();
+
+ let config = EngineConfig::default();
+ let engine = Engine::new(config).await.unwrap();
+ let model = engine.model("s1-mini".to_string()).await.unwrap().unwrap();
+ while let Some(update) = engine.download(&model).await.unwrap().next().await {
+ println!("Downloading: {}", update.progress());
+ }
+
+ let session = engine.text_to_speech(model).await.unwrap();
+ let result = session.synthesize("London is the capital of United Kingdom and one of the world’s most influential cities, known for its rich history, cultural diversity, and global significance in finance, politics, and the arts. Situated along the River Thames, the city blends historic landmarks like Tower of London and Buckingham Palace with modern architecture such as The Shard. London is also home to renowned institutions including the British Museum and vibrant areas like Covent Garden, offering a mix of history, entertainment, and innovation that attracts millions of visitors each year.".to_string()).await.unwrap();
+ let path = dirs::home_dir().unwrap().join("Desktop").join("output.wav").to_string_lossy().to_string();
+ result.pcm_batch.save_as_wav(path).unwrap();
+}