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 {
"Medium models",
new(string, string, string)[]
129 (
"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?download=true",
"https://huggingface.co/meta-llama/Meta-Llama-3.1-8B/blob/main/LICENSE"),
130 (
"Qwen 2.5 7B",
"https://huggingface.co/lmstudio-community/Qwen2.5-7B-Instruct-GGUF/resolve/main/Qwen2.5-7B-Instruct-Q4_K_M.gguf?download=true",
null),
131 (
"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?download=true",
null),
132 (
"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?download=true",
null),
133 (
"Gemma 2 9B it",
"https://huggingface.co/bartowski/gemma-2-9b-it-GGUF/resolve/main/gemma-2-9b-it-Q4_K_M.gguf?download=true",
"https://ai.google.dev/gemma/terms"),
134 (
"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?download=true",
null),
135 (
"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?download=true",
null),
137 {
"Small models",
new(string, string, string)[]
139 (
"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",
null),
140 (
"Phi 3.5 4B",
"https://huggingface.co/bartowski/Phi-3.5-mini-instruct-GGUF/resolve/main/Phi-3.5-mini-instruct-Q4_K_M.gguf",
null),
141 (
"Qwen 2.5 3B",
"https://huggingface.co/Qwen/Qwen2.5-3B-Instruct-GGUF/resolve/main/qwen2.5-3b-instruct-q4_k_m.gguf?download=true",
null),
143 {
"Tiny models",
new(string, string, string)[]
145 (
"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",
null),
146 (
"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?download=true",
null),
147 (
"Qwen 2 0.5B",
"https://huggingface.co/Qwen/Qwen2-0.5B-Instruct-GGUF/resolve/main/qwen2-0_5b-instruct-q4_k_m.gguf?download=true",
null),
148 (
"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?download=true",
null),
150 {
"RAG models",
new(string, string, string)[]
152 (
"All MiniLM L12 v2",
"https://huggingface.co/leliuga/all-MiniLM-L12-v2-GGUF/resolve/main/all-MiniLM-L12-v2.Q4_K_M.gguf",
null),
153 (
"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),
154 (
"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),
155 (
"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),
160 [
LLMUnity]
public static DebugModeType DebugMode = DebugModeType.All;
161 static string DebugModeKey =
"DebugMode";
162 public static bool FullLlamaLib =
false;
163 static string FullLlamaLibKey =
"FullLlamaLib";
164 static List<Callback<string>> errorCallbacks =
new List<Callback<string>>();
165 static readonly
object lockObject =
new object();
166 static Dictionary<string, Task> androidExtractTasks =
new Dictionary<string, Task>();
168 public enum DebugModeType
176 public static void Log(
string message)
178 if ((
int)DebugMode > (
int)DebugModeType.All)
return;
182 public static void LogWarning(
string message)
184 if ((
int)DebugMode > (
int)DebugModeType.Warning)
return;
185 Debug.LogWarning(message);
188 public static void LogError(
string message)
190 if ((
int)DebugMode > (
int)DebugModeType.Error)
return;
191 Debug.LogError(message);
192 foreach (Callback<string> errorCallback
in errorCallbacks) errorCallback(message);
195 static void LoadPlayerPrefs()
197 DebugMode = (DebugModeType)PlayerPrefs.GetInt(DebugModeKey, (
int)DebugModeType.All);
198 FullLlamaLib = PlayerPrefs.GetInt(FullLlamaLibKey, 0) == 1;
201 public static void SetDebugMode(DebugModeType newDebugMode)
203 if (DebugMode == newDebugMode)
return;
204 DebugMode = newDebugMode;
205 PlayerPrefs.SetInt(DebugModeKey, (
int)DebugMode);
210 public static void SetFullLlamaLib(
bool value)
212 if (FullLlamaLib == value)
return;
213 FullLlamaLib = value;
214 PlayerPrefs.SetInt(FullLlamaLibKey, value ? 1 : 0);
216 _ = DownloadLibrary();
221 public static string GetLibraryName(
string version)
223 return $
"undreamai-{version}-llamacpp";
226 public static string GetAssetPath(
string relPath =
"")
228 string assetsDir = Application.platform == RuntimePlatform.Android ? Application.persistentDataPath : Application.streamingAssetsPath;
229 return Path.Combine(assetsDir, relPath).Replace(
'\\',
'/');
232 public static string GetDownloadAssetPath(
string relPath =
"")
234 string assetsDir = (Application.platform == RuntimePlatform.Android || Application.platform == RuntimePlatform.IPhonePlayer) ? Application.persistentDataPath : Application.streamingAssetsPath;
235 return Path.Combine(assetsDir, relPath).Replace(
'\\',
'/');
239 [InitializeOnLoadMethod]
240 static async Task InitializeOnLoad()
243 await DownloadLibrary();
247 [RuntimeInitializeOnLoadMethod(RuntimeInitializeLoadType.BeforeSceneLoad)]
248 void InitializeOnLoad()
255 static Dictionary<string, ResumingWebClient> downloadClients =
new Dictionary<string, ResumingWebClient>();
257 public static void CancelDownload(
string savePath)
259 if (!downloadClients.ContainsKey(savePath))
return;
260 downloadClients[savePath].CancelDownloadAsync();
261 downloadClients.Remove(savePath);
264 public static async Task DownloadFile(
265 string fileUrl,
string savePath,
bool overwrite =
false,
266 Callback<string> callback =
null, Callback<float> progressCallback =
null
269 if (File.Exists(savePath) && !overwrite)
271 Log($
"File already exists at: {savePath}");
275 Log($
"Downloading {fileUrl} to {savePath}...");
276 string tmpPath = Path.Combine(Application.temporaryCachePath, Path.GetFileName(savePath));
278 ResumingWebClient client =
new ResumingWebClient();
279 downloadClients[savePath] = client;
280 await client.DownloadFileTaskAsyncResume(
new Uri(fileUrl), tmpPath, !overwrite, progressCallback);
281 downloadClients.Remove(savePath);
283 AssetDatabase.StartAssetEditing();
285 Directory.CreateDirectory(Path.GetDirectoryName(savePath));
286 File.Move(tmpPath, savePath);
288 AssetDatabase.StopAssetEditing();
290 Log($
"Download complete!");
293 progressCallback?.Invoke(1f);
294 callback?.Invoke(savePath);
297 public static async Task AndroidExtractFile(
string assetName,
bool overwrite =
false,
bool log =
true,
int chunkSize = 1024*1024)
302 if (!androidExtractTasks.TryGetValue(assetName, out extractionTask))
305 extractionTask = AndroidExtractFileOnce(assetName, overwrite, log, chunkSize);
307 extractionTask = Task.CompletedTask;
309 androidExtractTasks[assetName] = extractionTask;
312 await extractionTask;
315 public static async Task AndroidExtractFileOnce(
string assetName,
bool overwrite =
false,
bool log =
true,
int chunkSize = 1024*1024)
317 string source =
"jar:file://" + Application.dataPath +
"!/assets/" + assetName;
318 string target = GetAssetPath(assetName);
319 if (!overwrite && File.Exists(target))
321 if (log) Log($
"File {target} already exists");
325 Log($
"Extracting {source} to {target}");
328 UnityWebRequest www = UnityWebRequest.Get(source);
330 var operation = www.SendWebRequest();
332 while (!operation.isDone) await Task.Delay(1);
333 if (www.result != UnityWebRequest.Result.Success)
335 LogError(
"Failed to load file from StreamingAssets: " + www.error);
339 byte[] buffer =
new byte[chunkSize];
340 using (Stream responseStream =
new MemoryStream(www.downloadHandler.data))
341 using (FileStream fileStream =
new FileStream(target, FileMode.Create, FileAccess.Write))
344 while ((bytesRead = await responseStream.ReadAsync(buffer, 0, buffer.Length)) > 0)
346 await fileStream.WriteAsync(buffer, 0, bytesRead);
352 public static async Task AndroidExtractAsset(
string path,
bool overwrite =
false)
354 if (Application.platform != RuntimePlatform.Android)
return;
355 await AndroidExtractFile(Path.GetFileName(path), overwrite);
358 public static string GetFullPath(
string path)
360 return Path.GetFullPath(path).Replace(
'\\',
'/');
363 public static bool IsSubPath(
string childPath,
string parentPath)
365 return GetFullPath(childPath).StartsWith(GetFullPath(parentPath), StringComparison.OrdinalIgnoreCase);
368 public static string RelativePath(
string fullPath,
string basePath)
371 string fullParentPath = GetFullPath(basePath).TrimEnd(
'/');
372 string fullChildPath = GetFullPath(fullPath);
374 string relativePath = fullChildPath;
375 if (fullChildPath.StartsWith(fullParentPath, StringComparison.OrdinalIgnoreCase))
377 relativePath = fullChildPath.Substring(fullParentPath.Length);
378 while (relativePath.StartsWith(
"/")) relativePath = relativePath.Substring(1);
385 [HideInInspector]
public static float libraryProgress = 1;
387 public static void CreateEmptyFile(
string path)
389 File.Create(path).Dispose();
392 static void ExtractInsideDirectory(
string zipPath,
string extractPath,
bool overwrite =
true)
394 using (ZipArchive archive = ZipFile.OpenRead(zipPath))
396 foreach (ZipArchiveEntry entry
in archive.Entries)
398 if (
string.IsNullOrEmpty(entry.Name))
continue;
399 string destinationPath = Path.Combine(extractPath, entry.FullName);
400 Directory.CreateDirectory(Path.GetDirectoryName(destinationPath));
401 entry.ExtractToFile(destinationPath, overwrite);
406 static async Task DownloadAndExtractInsideDirectory(
string url,
string path,
string setupDir)
408 string urlName = Path.GetFileName(url);
409 string setupFile = Path.Combine(setupDir, urlName +
".complete");
410 if (File.Exists(setupFile))
return;
412 string zipPath = Path.Combine(Application.temporaryCachePath, urlName);
413 await DownloadFile(url, zipPath,
true,
null, SetLibraryProgress);
415 AssetDatabase.StartAssetEditing();
416 ExtractInsideDirectory(zipPath, path);
417 CreateEmptyFile(setupFile);
418 AssetDatabase.StopAssetEditing();
420 File.Delete(zipPath);
423 static void DeleteEarlierVersions()
425 List<string> assetPathSubDirs =
new List<string>();
426 foreach (
string dir
in new string[] {GetAssetPath(), Path.Combine(Application.dataPath,
"Plugins",
"Android")})
428 if (Directory.Exists(dir)) assetPathSubDirs.AddRange(Directory.GetDirectories(dir));
431 Regex regex =
new Regex(GetLibraryName(
"(.+)"));
432 foreach (
string assetPathSubDir
in assetPathSubDirs)
434 Match match = regex.Match(Path.GetFileName(assetPathSubDir));
437 string version = match.Groups[1].Value;
440 Debug.Log($
"Deleting other LLMUnity version folder: {assetPathSubDir}");
441 Directory.Delete(assetPathSubDir,
true);
442 if (File.Exists(assetPathSubDir +
".meta")) File.Delete(assetPathSubDir +
".meta");
448 static async Task DownloadLibrary()
450 if (libraryProgress < 1)
return;
455 DeleteEarlierVersions();
457 string setupDir = Path.Combine(
libraryPath,
"setup");
458 Directory.CreateDirectory(setupDir);
474 private static void SetLibraryProgress(
float progress)
476 libraryProgress = Math.Min(0.99f, progress);
479 public static string AddAsset(
string assetPath)
481 if (!File.Exists(assetPath))
483 LogError($
"{assetPath} does not exist!");
486 string assetDir = GetAssetPath();
487 if (IsSubPath(assetPath, assetDir))
return RelativePath(assetPath, assetDir);
489 string filename = Path.GetFileName(assetPath);
490 string fullPath = GetAssetPath(filename);
491 AssetDatabase.StartAssetEditing();
492 foreach (
string path
in new string[] {fullPath, fullPath +
".meta"})
494 if (File.Exists(path)) File.Delete(path);
496 File.Copy(assetPath, fullPath);
497 AssetDatabase.StopAssetEditing();
507 errorCallbacks.Add(callback);
513 errorCallbacks.Remove(callback);
519 errorCallbacks.Clear();
522 public static int GetMaxFreqKHz(
int cpuId)
524 string[] paths =
new string[]
526 $
"/sys/devices/system/cpu/cpufreq/stats/cpu{cpuId}/time_in_state",
527 $
"/sys/devices/system/cpu/cpu{cpuId}/cpufreq/stats/time_in_state",
528 $
"/sys/devices/system/cpu/cpu{cpuId}/cpufreq/cpuinfo_max_freq"
531 foreach (var path
in paths)
533 if (!File.Exists(path))
continue;
536 using (StreamReader sr =
new StreamReader(path))
539 while ((line = sr.ReadLine()) !=
null)
541 string[] parts = line.Split(
' ');
542 if (parts.Length > 0 &&
int.TryParse(parts[0], out
int freqKHz))
544 if (freqKHz > maxFreqKHz)
546 maxFreqKHz = freqKHz;
551 if (maxFreqKHz != 0)
return maxFreqKHz;
556 public static bool IsSmtCpu(
int cpuId)
558 string[] paths =
new string[]
560 $
"/sys/devices/system/cpu/cpu{cpuId}/topology/core_cpus_list",
561 $
"/sys/devices/system/cpu/cpu{cpuId}/topology/thread_siblings_list"
564 foreach (var path
in paths)
566 if (!File.Exists(path))
continue;
567 using (StreamReader sr =
new StreamReader(path))
570 while ((line = sr.ReadLine()) !=
null)
572 if (line.Contains(
",") || line.Contains(
"-"))
588 int maxFreqKHzMin =
int.MaxValue;
589 int maxFreqKHzMax = 0;
590 List<int> cpuMaxFreqKHz =
new List<int>();
591 List<bool> cpuIsSmtCpu =
new List<bool>();
595 string cpuPath =
"/sys/devices/system/cpu/";
597 if (Directory.Exists(cpuPath))
599 foreach (
string cpuDir
in Directory.GetDirectories(cpuPath))
601 string dirName = Path.GetFileName(cpuDir);
602 if (!dirName.StartsWith(
"cpu"))
continue;
603 if (!
int.TryParse(dirName.Substring(3), out coreIndex))
continue;
605 int maxFreqKHz = GetMaxFreqKHz(coreIndex);
606 cpuMaxFreqKHz.Add(maxFreqKHz);
607 if (maxFreqKHz > maxFreqKHzMax) maxFreqKHzMax = maxFreqKHz;
608 if (maxFreqKHz < maxFreqKHzMin) maxFreqKHzMin = maxFreqKHz;
609 cpuIsSmtCpu.Add(IsSmtCpu(coreIndex));
619 int numCores = SystemInfo.processorCount;
620 int maxFreqKHzMedium = (maxFreqKHzMin + maxFreqKHzMax) / 2;
621 if (maxFreqKHzMedium == maxFreqKHzMax) numBigCores = numCores;
624 for (
int i = 0; i < cpuMaxFreqKHz.Count; i++)
626 if (cpuIsSmtCpu[i] || cpuMaxFreqKHz[i] >= maxFreqKHzMedium) numBigCores++;
630 if (numBigCores == 0) numBigCores = SystemInfo.processorCount / 2;
631 else numBigCores = Math.Min(numBigCores, SystemInfo.processorCount);
642 List<int> capacities =
new List<int>();
643 int minCapacity =
int.MaxValue;
646 string cpuPath =
"/sys/devices/system/cpu/";
648 if (Directory.Exists(cpuPath))
650 foreach (
string cpuDir
in Directory.GetDirectories(cpuPath))
652 string dirName = Path.GetFileName(cpuDir);
653 if (!dirName.StartsWith(
"cpu"))
continue;
654 if (!
int.TryParse(dirName.Substring(3), out coreIndex))
continue;
656 string capacityPath = Path.Combine(cpuDir,
"cpu_capacity");
657 if (!File.Exists(capacityPath))
break;
659 int capacity =
int.Parse(File.ReadAllText(capacityPath).Trim());
660 capacities.Add(capacity);
661 if (minCapacity > capacity) minCapacity = capacity;
671 foreach (
int capacity
in capacities)
673 if (capacity >= 2 * minCapacity) numBigCores++;
676 if (numBigCores == 0 || numBigCores > SystemInfo.processorCount) numBigCores = SystemInfo.processorCount;