108 public static string LlamaLibReleaseURL = $
"https://github.com/undreamai/LlamaLib/releases/download/{LlamaLibVersion}";
114 public static string LlamaLibURL = $
"{LlamaLibReleaseURL}/{libraryName}.zip";
118 public static string LLMUnityStore = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData),
"LLMUnity");
125 [HideInInspector]
public static readonly Dictionary<string, (string, string, string)[]>
modelOptions =
new Dictionary<
string, (
string,
string,
string)[]>()
127 {
"Large models (more than 10B)",
new(string, string, string)[]
129 (
"Gemma 3 12B",
"https://huggingface.co/lmstudio-community/gemma-3-12b-it-GGUF/resolve/main/gemma-3-12b-it-Q4_K_M.gguf",
"https://ai.google.dev/gemma/terms"),
130 (
"Phi 4 14B",
"https://huggingface.co/bartowski/phi-4-GGUF/resolve/main/phi-4-Q4_K_M.gguf",
null),
131 (
"Qwen 2.5 14B",
"https://huggingface.co/lmstudio-community/Qwen2.5-14B-Instruct-GGUF/resolve/main/Qwen2.5-14B-Instruct-Q4_K_M.gguf",
null),
132 (
"DeepSeek R1 Distill Qwen 14B",
"https://huggingface.co/lmstudio-community/DeepSeek-R1-Distill-Qwen-14B-GGUF/resolve/main/DeepSeek-R1-Distill-Qwen-14B-Q4_K_M.gguf",
null),
134 {
"Medium models (up to 10B)",
new(string, string, string)[]
136 (
"Llama 3.1 8B",
"https://huggingface.co/bartowski/Meta-Llama-3.1-8B-Instruct-GGUF/resolve/main/Meta-Llama-3.1-8B-Instruct-Q4_K_M.gguf",
"https://huggingface.co/meta-llama/Meta-Llama-3.1-8B/blob/main/LICENSE"),
137 (
"Qwen 2.5 7B",
"https://huggingface.co/lmstudio-community/Qwen2.5-7B-Instruct-GGUF/resolve/main/Qwen2.5-7B-Instruct-Q4_K_M.gguf",
null),
138 (
"DeepSeek R1 Distill Llama 8B",
"https://huggingface.co/lmstudio-community/DeepSeek-R1-Distill-Llama-8B-GGUF/resolve/main/DeepSeek-R1-Distill-Llama-8B-Q4_K_M.gguf",
null),
139 (
"DeepSeek R1 Distill Qwen 7B",
"https://huggingface.co/lmstudio-community/DeepSeek-R1-Distill-Qwen-7B-GGUF/resolve/main/DeepSeek-R1-Distill-Qwen-7B-Q4_K_M.gguf",
null),
140 (
"Gemma 2 9B it",
"https://huggingface.co/bartowski/gemma-2-9b-it-GGUF/resolve/main/gemma-2-9b-it-Q4_K_M.gguf",
"https://ai.google.dev/gemma/terms"),
141 (
"Mistral 7B Instruct v0.2",
"https://huggingface.co/TheBloke/Mistral-7B-Instruct-v0.2-GGUF/resolve/main/mistral-7b-instruct-v0.2.Q4_K_M.gguf",
null),
142 (
"OpenHermes 2.5 7B",
"https://huggingface.co/TheBloke/OpenHermes-2.5-Mistral-7B-GGUF/resolve/main/openhermes-2.5-mistral-7b.Q4_K_M.gguf",
null),
144 {
"Small models (up to 5B)",
new(string, string, string)[]
146 (
"Llama 3.2 3B",
"https://huggingface.co/hugging-quants/Llama-3.2-3B-Instruct-Q4_K_M-GGUF/resolve/main/llama-3.2-3b-instruct-q4_k_m.gguf",
"https://huggingface.co/meta-llama/Llama-3.2-1B/blob/main/LICENSE.txt"),
147 (
"Gemma 3 4B",
"https://huggingface.co/lmstudio-community/gemma-3-4b-it-GGUF/resolve/main/gemma-3-4b-it-Q4_K_M.gguf",
"https://ai.google.dev/gemma/terms"),
148 (
"Phi 4 4B",
"https://huggingface.co/bartowski/microsoft_Phi-4-mini-instruct-GGUF/resolve/main/microsoft_Phi-4-mini-instruct-Q4_K_M.gguf",
null),
149 (
"Qwen 2.5 3B",
"https://huggingface.co/Qwen/Qwen2.5-3B-Instruct-GGUF/resolve/main/qwen2.5-3b-instruct-q4_k_m.gguf",
null),
151 {
"Tiny models (up to 2B)",
new(string, string, string)[]
153 (
"Llama 3.2 1B",
"https://huggingface.co/hugging-quants/Llama-3.2-1B-Instruct-Q4_K_M-GGUF/resolve/main/llama-3.2-1b-instruct-q4_k_m.gguf",
"https://huggingface.co/meta-llama/Llama-3.2-1B/blob/main/LICENSE.txt"),
154 (
"Gemma 3 1B",
"https://huggingface.co/lmstudio-community/gemma-3-1b-it-GGUF/resolve/main/gemma-3-1b-it-Q4_K_M.gguf",
"https://ai.google.dev/gemma/terms"),
155 (
"Qwen 2.5 1.5B",
"https://huggingface.co/Qwen/Qwen2.5-1.5B-Instruct-GGUF/resolve/main/qwen2.5-1.5b-instruct-q4_k_m.gguf",
null),
156 (
"Qwen 2 0.5B",
"https://huggingface.co/Qwen/Qwen2-0.5B-Instruct-GGUF/resolve/main/qwen2-0_5b-instruct-q4_k_m.gguf",
null),
157 (
"DeepSeek R1 Distill Qwen 1.5B",
"https://huggingface.co/lmstudio-community/DeepSeek-R1-Distill-Qwen-1.5B-GGUF/resolve/main/DeepSeek-R1-Distill-Qwen-1.5B-Q4_K_M.gguf",
null),
159 {
"RAG models",
new(string, string, string)[]
161 (
"All MiniLM L12 v2",
"https://huggingface.co/leliuga/all-MiniLM-L12-v2-GGUF/resolve/main/all-MiniLM-L12-v2.Q4_K_M.gguf",
null),
162 (
"BGE large en v1.5",
"https://huggingface.co/CompendiumLabs/bge-large-en-v1.5-gguf/resolve/main/bge-large-en-v1.5-q4_k_m.gguf",
null),
163 (
"BGE base en v1.5",
"https://huggingface.co/CompendiumLabs/bge-base-en-v1.5-gguf/resolve/main/bge-base-en-v1.5-q4_k_m.gguf",
null),
164 (
"BGE small en v1.5",
"https://huggingface.co/CompendiumLabs/bge-small-en-v1.5-gguf/resolve/main/bge-small-en-v1.5-q4_k_m.gguf",
null),
169 [
LLMUnity]
public static DebugModeType DebugMode = DebugModeType.All;
170 static string DebugModeKey =
"DebugMode";
171 public static bool FullLlamaLib =
false;
172 static string FullLlamaLibKey =
"FullLlamaLib";
173 static List<Callback<string>> errorCallbacks =
new List<Callback<string>>();
174 static readonly
object lockObject =
new object();
175 static Dictionary<string, Task> androidExtractTasks =
new Dictionary<string, Task>();
177 public enum DebugModeType
185 public static void Log(
string message)
187 if ((
int)DebugMode > (
int)DebugModeType.All)
return;
191 public static void LogWarning(
string message)
193 if ((
int)DebugMode > (
int)DebugModeType.Warning)
return;
194 Debug.LogWarning(message);
197 public static void LogError(
string message)
199 if ((
int)DebugMode > (
int)DebugModeType.Error)
return;
200 Debug.LogError(message);
201 foreach (Callback<string> errorCallback
in errorCallbacks) errorCallback(message);
204 static void LoadPlayerPrefs()
206 DebugMode = (DebugModeType)PlayerPrefs.GetInt(DebugModeKey, (
int)DebugModeType.All);
207 FullLlamaLib = PlayerPrefs.GetInt(FullLlamaLibKey, 0) == 1;
210 public static void SetDebugMode(DebugModeType newDebugMode)
212 if (DebugMode == newDebugMode)
return;
213 DebugMode = newDebugMode;
214 PlayerPrefs.SetInt(DebugModeKey, (
int)DebugMode);
219 public static void SetFullLlamaLib(
bool value)
221 if (FullLlamaLib == value)
return;
222 FullLlamaLib = value;
223 PlayerPrefs.SetInt(FullLlamaLibKey, value ? 1 : 0);
225 _ = DownloadLibrary();
230 public static string GetLibraryName(
string version)
232 return $
"undreamai-{version}-llamacpp";
235 public static string GetAssetPath(
string relPath =
"")
237 string assetsDir = Application.platform == RuntimePlatform.Android ? Application.persistentDataPath : Application.streamingAssetsPath;
238 return Path.Combine(assetsDir, relPath).Replace(
'\\',
'/');
241 public static string GetDownloadAssetPath(
string relPath =
"")
243 string assetsDir = (Application.platform == RuntimePlatform.Android || Application.platform == RuntimePlatform.IPhonePlayer || Application.platform == RuntimePlatform.VisionOS) ? Application.persistentDataPath : Application.streamingAssetsPath;
244 return Path.Combine(assetsDir, relPath).Replace(
'\\',
'/');
248 [InitializeOnLoadMethod]
249 static async Task InitializeOnLoad()
252 await DownloadLibrary();
256 [RuntimeInitializeOnLoadMethod(RuntimeInitializeLoadType.BeforeSceneLoad)]
257 void InitializeOnLoad()
264 static Dictionary<string, ResumingWebClient> downloadClients =
new Dictionary<string, ResumingWebClient>();
266 public static void CancelDownload(
string savePath)
268 if (!downloadClients.ContainsKey(savePath))
return;
269 downloadClients[savePath].CancelDownloadAsync();
270 downloadClients.Remove(savePath);
273 public static async Task DownloadFile(
274 string fileUrl,
string savePath,
bool overwrite =
false,
275 Callback<string> callback =
null, Callback<float> progressCallback =
null
278 if (File.Exists(savePath) && !overwrite)
280 Log($
"File already exists at: {savePath}");
284 Log($
"Downloading {fileUrl} to {savePath}...");
285 string tmpPath = Path.Combine(Application.temporaryCachePath, Path.GetFileName(savePath));
287 ResumingWebClient client =
new ResumingWebClient();
288 downloadClients[savePath] = client;
289 await client.DownloadFileTaskAsyncResume(
new Uri(fileUrl), tmpPath, !overwrite, progressCallback);
290 downloadClients.Remove(savePath);
292 AssetDatabase.StartAssetEditing();
294 Directory.CreateDirectory(Path.GetDirectoryName(savePath));
295 File.Move(tmpPath, savePath);
297 AssetDatabase.StopAssetEditing();
299 Log($
"Download complete!");
302 progressCallback?.Invoke(1f);
303 callback?.Invoke(savePath);
306 public static async Task AndroidExtractFile(
string assetName,
bool overwrite =
false,
bool log =
true,
int chunkSize = 1024*1024)
311 if (!androidExtractTasks.TryGetValue(assetName, out extractionTask))
314 extractionTask = AndroidExtractFileOnce(assetName, overwrite, log, chunkSize);
316 extractionTask = Task.CompletedTask;
318 androidExtractTasks[assetName] = extractionTask;
321 await extractionTask;
324 public static async Task AndroidExtractFileOnce(
string assetName,
bool overwrite =
false,
bool log =
true,
int chunkSize = 1024*1024)
326 string source =
"jar:file://" + Application.dataPath +
"!/assets/" + assetName;
327 string target = GetAssetPath(assetName);
328 if (!overwrite && File.Exists(target))
330 if (log) Log($
"File {target} already exists");
334 Log($
"Extracting {source} to {target}");
337 UnityWebRequest www = UnityWebRequest.Get(source);
339 var operation = www.SendWebRequest();
341 while (!operation.isDone) await Task.Delay(1);
342 if (www.result != UnityWebRequest.Result.Success)
344 LogError(
"Failed to load file from StreamingAssets: " + www.error);
348 byte[] buffer =
new byte[chunkSize];
349 using (Stream responseStream =
new MemoryStream(www.downloadHandler.data))
350 using (FileStream fileStream =
new FileStream(target, FileMode.Create, FileAccess.Write))
353 while ((bytesRead = await responseStream.ReadAsync(buffer, 0, buffer.Length)) > 0)
355 await fileStream.WriteAsync(buffer, 0, bytesRead);
361 public static async Task AndroidExtractAsset(
string path,
bool overwrite =
false)
363 if (Application.platform != RuntimePlatform.Android)
return;
364 await AndroidExtractFile(Path.GetFileName(path), overwrite);
367 public static string GetFullPath(
string path)
369 return Path.GetFullPath(path).Replace(
'\\',
'/');
372 public static bool IsSubPath(
string childPath,
string parentPath)
374 return GetFullPath(childPath).StartsWith(GetFullPath(parentPath), StringComparison.OrdinalIgnoreCase);
377 public static string RelativePath(
string fullPath,
string basePath)
380 string fullParentPath = GetFullPath(basePath).TrimEnd(
'/');
381 string fullChildPath = GetFullPath(fullPath);
383 string relativePath = fullChildPath;
384 if (fullChildPath.StartsWith(fullParentPath, StringComparison.OrdinalIgnoreCase))
386 relativePath = fullChildPath.Substring(fullParentPath.Length);
387 while (relativePath.StartsWith(
"/")) relativePath = relativePath.Substring(1);
392 public static string SearchDirectory(
string directory,
string targetFileName)
394 string[] files = Directory.GetFiles(directory, targetFileName);
395 if (files.Length > 0)
return files[0];
396 string[] subdirectories = Directory.GetDirectories(directory);
397 foreach (var subdirectory
in subdirectories)
399 string result = SearchDirectory(subdirectory, targetFileName);
400 if (result !=
null)
return result;
407 [HideInInspector]
public static float libraryProgress = 1;
409 public static void CreateEmptyFile(
string path)
411 File.Create(path).Dispose();
414 static void ExtractInsideDirectory(
string zipPath,
string extractPath,
bool overwrite =
true)
416 using (ZipArchive archive = ZipFile.OpenRead(zipPath))
418 foreach (ZipArchiveEntry entry
in archive.Entries)
420 if (
string.IsNullOrEmpty(entry.Name))
continue;
421 string destinationPath = Path.Combine(extractPath, entry.FullName);
422 Directory.CreateDirectory(Path.GetDirectoryName(destinationPath));
423 entry.ExtractToFile(destinationPath, overwrite);
428 static async Task DownloadAndExtractInsideDirectory(
string url,
string path,
string setupDir)
430 string urlName = Path.GetFileName(url);
431 string setupFile = Path.Combine(setupDir, urlName +
".complete");
432 if (File.Exists(setupFile))
return;
434 string zipPath = Path.Combine(Application.temporaryCachePath, urlName);
435 await DownloadFile(url, zipPath,
true,
null, SetLibraryProgress);
437 AssetDatabase.StartAssetEditing();
438 ExtractInsideDirectory(zipPath, path);
439 CreateEmptyFile(setupFile);
440 AssetDatabase.StopAssetEditing();
442 File.Delete(zipPath);
445 static void DeleteEarlierVersions()
447 List<string> assetPathSubDirs =
new List<string>();
448 foreach (
string dir
in new string[] {GetAssetPath(), Path.Combine(Application.dataPath,
"Plugins",
"Android")})
450 if (Directory.Exists(dir)) assetPathSubDirs.AddRange(Directory.GetDirectories(dir));
453 Regex regex =
new Regex(GetLibraryName(
"(.+)"));
454 foreach (
string assetPathSubDir
in assetPathSubDirs)
456 Match match = regex.Match(Path.GetFileName(assetPathSubDir));
459 string version = match.Groups[1].Value;
462 Debug.Log($
"Deleting other LLMUnity version folder: {assetPathSubDir}");
463 Directory.Delete(assetPathSubDir,
true);
464 if (File.Exists(assetPathSubDir +
".meta")) File.Delete(assetPathSubDir +
".meta");
470 static async Task DownloadLibrary()
472 if (libraryProgress < 1)
return;
477 DeleteEarlierVersions();
479 string setupDir = Path.Combine(
libraryPath,
"setup");
480 Directory.CreateDirectory(setupDir);
496 private static void SetLibraryProgress(
float progress)
498 libraryProgress = Math.Min(0.99f, progress);
501 public static string AddAsset(
string assetPath)
503 if (!File.Exists(assetPath))
505 LogError($
"{assetPath} does not exist!");
508 string assetDir = GetAssetPath();
509 if (IsSubPath(assetPath, assetDir))
return RelativePath(assetPath, assetDir);
511 string filename = Path.GetFileName(assetPath);
512 string fullPath = GetAssetPath(filename);
513 AssetDatabase.StartAssetEditing();
514 foreach (
string path
in new string[] {fullPath, fullPath +
".meta"})
516 if (File.Exists(path)) File.Delete(path);
518 File.Copy(assetPath, fullPath);
519 AssetDatabase.StopAssetEditing();
529 errorCallbacks.Add(callback);
535 errorCallbacks.Remove(callback);
541 errorCallbacks.Clear();
544 public static int GetMaxFreqKHz(
int cpuId)
546 string[] paths =
new string[]
548 $
"/sys/devices/system/cpu/cpufreq/stats/cpu{cpuId}/time_in_state",
549 $
"/sys/devices/system/cpu/cpu{cpuId}/cpufreq/stats/time_in_state",
550 $
"/sys/devices/system/cpu/cpu{cpuId}/cpufreq/cpuinfo_max_freq"
553 foreach (var path
in paths)
555 if (!File.Exists(path))
continue;
558 using (StreamReader sr =
new StreamReader(path))
561 while ((line = sr.ReadLine()) !=
null)
563 string[] parts = line.Split(
' ');
564 if (parts.Length > 0 &&
int.TryParse(parts[0], out
int freqKHz))
566 if (freqKHz > maxFreqKHz)
568 maxFreqKHz = freqKHz;
573 if (maxFreqKHz != 0)
return maxFreqKHz;
578 public static bool IsSmtCpu(
int cpuId)
580 string[] paths =
new string[]
582 $
"/sys/devices/system/cpu/cpu{cpuId}/topology/core_cpus_list",
583 $
"/sys/devices/system/cpu/cpu{cpuId}/topology/thread_siblings_list"
586 foreach (var path
in paths)
588 if (!File.Exists(path))
continue;
589 using (StreamReader sr =
new StreamReader(path))
592 while ((line = sr.ReadLine()) !=
null)
594 if (line.Contains(
",") || line.Contains(
"-"))
610 int maxFreqKHzMin =
int.MaxValue;
611 int maxFreqKHzMax = 0;
612 List<int> cpuMaxFreqKHz =
new List<int>();
613 List<bool> cpuIsSmtCpu =
new List<bool>();
617 string cpuPath =
"/sys/devices/system/cpu/";
619 if (Directory.Exists(cpuPath))
621 foreach (
string cpuDir
in Directory.GetDirectories(cpuPath))
623 string dirName = Path.GetFileName(cpuDir);
624 if (!dirName.StartsWith(
"cpu"))
continue;
625 if (!
int.TryParse(dirName.Substring(3), out coreIndex))
continue;
627 int maxFreqKHz = GetMaxFreqKHz(coreIndex);
628 cpuMaxFreqKHz.Add(maxFreqKHz);
629 if (maxFreqKHz > maxFreqKHzMax) maxFreqKHzMax = maxFreqKHz;
630 if (maxFreqKHz < maxFreqKHzMin) maxFreqKHzMin = maxFreqKHz;
631 cpuIsSmtCpu.Add(IsSmtCpu(coreIndex));
641 int numCores = SystemInfo.processorCount;
642 int maxFreqKHzMedium = (maxFreqKHzMin + maxFreqKHzMax) / 2;
643 if (maxFreqKHzMedium == maxFreqKHzMax) numBigCores = numCores;
646 for (
int i = 0; i < cpuMaxFreqKHz.Count; i++)
648 if (cpuIsSmtCpu[i] || cpuMaxFreqKHz[i] >= maxFreqKHzMedium) numBigCores++;
652 if (numBigCores == 0) numBigCores = SystemInfo.processorCount / 2;
653 else numBigCores = Math.Min(numBigCores, SystemInfo.processorCount);
664 List<int> capacities =
new List<int>();
665 int minCapacity =
int.MaxValue;
668 string cpuPath =
"/sys/devices/system/cpu/";
670 if (Directory.Exists(cpuPath))
672 foreach (
string cpuDir
in Directory.GetDirectories(cpuPath))
674 string dirName = Path.GetFileName(cpuDir);
675 if (!dirName.StartsWith(
"cpu"))
continue;
676 if (!
int.TryParse(dirName.Substring(3), out coreIndex))
continue;
678 string capacityPath = Path.Combine(cpuDir,
"cpu_capacity");
679 if (!File.Exists(capacityPath))
break;
681 int capacity =
int.Parse(File.ReadAllText(capacityPath).Trim());
682 capacities.Add(capacity);
683 if (minCapacity > capacity) minCapacity = capacity;
693 foreach (
int capacity
in capacities)
695 if (capacity >= 2 * minCapacity) numBigCores++;
698 if (numBigCores == 0 || numBigCores > SystemInfo.processorCount) numBigCores = SystemInfo.processorCount;