107 public static string LlamaLibReleaseURL = $
"https://github.com/undreamai/LlamaLib/releases/download/{LlamaLibVersion}";
109 public static string LlamaLibURL = $
"{LlamaLibReleaseURL}/undreamai-{LlamaLibVersion}-llamacpp.zip";
111 public static string LlamaLibExtensionURL = $
"{LlamaLibReleaseURL}/undreamai-{LlamaLibVersion}-llamacpp-full.zip";
115 public static string LLMUnityStore = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData),
"LLMUnity");
122 [HideInInspector]
public static readonly Dictionary<string, (string, string, string)[]>
modelOptions =
new Dictionary<
string, (
string,
string,
string)[]>()
124 {
"Medium models",
new(string, string, string)[]
126 (
"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"),
127 (
"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),
128 (
"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"),
129 (
"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),
131 {
"Small models",
new(string, string, string)[]
133 (
"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),
134 (
"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),
136 {
"Tiny models",
new(string, string, string)[]
138 (
"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),
139 (
"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),
141 {
"RAG models",
new(string, string, string)[]
143 (
"All MiniLM L12 v2",
"https://huggingface.co/leliuga/all-MiniLM-L12-v2-GGUF/resolve/main/all-MiniLM-L12-v2.Q4_K_M.gguf",
null),
144 (
"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),
145 (
"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),
146 (
"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),
151 [
LLMUnity]
public static DebugModeType DebugMode = DebugModeType.All;
152 static string DebugModeKey =
"DebugMode";
153 public static bool FullLlamaLib =
false;
154 static string FullLlamaLibKey =
"FullLlamaLib";
155 static List<Callback<string>> errorCallbacks =
new List<Callback<string>>();
156 static readonly
object lockObject =
new object();
157 static Dictionary<string, Task> androidExtractTasks =
new Dictionary<string, Task>();
159 public enum DebugModeType
167 public static void Log(
string message)
169 if ((
int)DebugMode > (
int)DebugModeType.All)
return;
173 public static void LogWarning(
string message)
175 if ((
int)DebugMode > (
int)DebugModeType.Warning)
return;
176 Debug.LogWarning(message);
179 public static void LogError(
string message)
181 if ((
int)DebugMode > (
int)DebugModeType.Error)
return;
182 Debug.LogError(message);
183 foreach (Callback<string> errorCallback
in errorCallbacks) errorCallback(message);
186 static void LoadPlayerPrefs()
188 DebugMode = (DebugModeType)PlayerPrefs.GetInt(DebugModeKey, (
int)DebugModeType.All);
189 FullLlamaLib = PlayerPrefs.GetInt(FullLlamaLibKey, 0) == 1;
192 public static void SetDebugMode(DebugModeType newDebugMode)
194 if (DebugMode == newDebugMode)
return;
195 DebugMode = newDebugMode;
196 PlayerPrefs.SetInt(DebugModeKey, (
int)DebugMode);
201 public static void SetFullLlamaLib(
bool value)
203 if (FullLlamaLib == value)
return;
204 FullLlamaLib = value;
205 PlayerPrefs.SetInt(FullLlamaLibKey, value ? 1 : 0);
207 _ = DownloadLibrary();
212 public static string GetAssetPath(
string relPath =
"")
215 string assetsDir = Application.platform == RuntimePlatform.Android ? Application.persistentDataPath : Application.streamingAssetsPath;
216 return Path.Combine(assetsDir, relPath).Replace(
'\\',
'/');
220 [InitializeOnLoadMethod]
221 static async Task InitializeOnLoad()
224 await DownloadLibrary();
228 [RuntimeInitializeOnLoadMethod(RuntimeInitializeLoadType.BeforeSceneLoad)]
229 void InitializeOnLoad()
236 static Dictionary<string, ResumingWebClient> downloadClients =
new Dictionary<string, ResumingWebClient>();
238 public static void CancelDownload(
string savePath)
240 if (!downloadClients.ContainsKey(savePath))
return;
241 downloadClients[savePath].CancelDownloadAsync();
242 downloadClients.Remove(savePath);
245 public static async Task DownloadFile(
246 string fileUrl,
string savePath,
bool overwrite =
false,
247 Callback<string> callback =
null, Callback<float> progressCallback =
null
250 if (File.Exists(savePath) && !overwrite)
252 Log($
"File already exists at: {savePath}");
256 Log($
"Downloading {fileUrl} to {savePath}...");
257 string tmpPath = Path.Combine(Application.temporaryCachePath, Path.GetFileName(savePath));
259 ResumingWebClient client =
new ResumingWebClient();
260 downloadClients[savePath] = client;
261 await client.DownloadFileTaskAsyncResume(
new Uri(fileUrl), tmpPath, !overwrite, progressCallback);
262 downloadClients.Remove(savePath);
264 AssetDatabase.StartAssetEditing();
266 Directory.CreateDirectory(Path.GetDirectoryName(savePath));
267 File.Move(tmpPath, savePath);
269 AssetDatabase.StopAssetEditing();
271 Log($
"Download complete!");
274 progressCallback?.Invoke(1f);
275 callback?.Invoke(savePath);
278 public static async Task AndroidExtractFile(
string assetName,
bool overwrite =
false,
bool log =
true,
int chunkSize = 1024*1024)
283 if (!androidExtractTasks.TryGetValue(assetName, out extractionTask))
285 extractionTask = AndroidExtractFileOnce(assetName, overwrite, log, chunkSize);
286 androidExtractTasks[assetName] = extractionTask;
289 await extractionTask;
292 public static async Task AndroidExtractFileOnce(
string assetName,
bool overwrite =
false,
bool log =
true,
int chunkSize = 1024*1024)
294 string source =
"jar:file://" + Application.dataPath +
"!/assets/" + assetName;
295 string target = GetAssetPath(assetName);
296 if (!overwrite && File.Exists(target))
298 if (log) Log($
"File {target} already exists");
302 Log($
"Extracting {source} to {target}");
305 UnityWebRequest www = UnityWebRequest.Get(source);
307 var operation = www.SendWebRequest();
309 while (!operation.isDone) await Task.Delay(1);
310 if (www.result != UnityWebRequest.Result.Success)
312 LogError(
"Failed to load file from StreamingAssets: " + www.error);
316 byte[] buffer =
new byte[chunkSize];
317 using (Stream responseStream =
new MemoryStream(www.downloadHandler.data))
318 using (FileStream fileStream =
new FileStream(target, FileMode.Create, FileAccess.Write))
321 while ((bytesRead = await responseStream.ReadAsync(buffer, 0, buffer.Length)) > 0)
323 await fileStream.WriteAsync(buffer, 0, bytesRead);
329 public static async Task AndroidExtractAsset(
string path,
bool overwrite =
false)
331 if (Application.platform != RuntimePlatform.Android)
return;
332 await AndroidExtractFile(Path.GetFileName(path), overwrite);
335 public static string GetFullPath(
string path)
337 return Path.GetFullPath(path).Replace(
'\\',
'/');
340 public static bool IsSubPath(
string childPath,
string parentPath)
342 return GetFullPath(childPath).StartsWith(GetFullPath(parentPath), StringComparison.OrdinalIgnoreCase);
345 public static string RelativePath(
string fullPath,
string basePath)
348 string fullParentPath = GetFullPath(basePath).TrimEnd(
'/');
349 string fullChildPath = GetFullPath(fullPath);
351 string relativePath = fullChildPath;
352 if (fullChildPath.StartsWith(fullParentPath, StringComparison.OrdinalIgnoreCase))
354 relativePath = fullChildPath.Substring(fullParentPath.Length);
355 while (relativePath.StartsWith(
"/")) relativePath = relativePath.Substring(1);
362 [HideInInspector]
public static float libraryProgress = 1;
364 public static void CreateEmptyFile(
string path)
366 File.Create(path).Dispose();
369 static void ExtractInsideDirectory(
string zipPath,
string extractPath,
bool overwrite =
true)
371 using (ZipArchive archive = ZipFile.OpenRead(zipPath))
373 foreach (ZipArchiveEntry entry
in archive.Entries)
375 if (
string.IsNullOrEmpty(entry.Name))
continue;
376 string destinationPath = Path.Combine(extractPath, entry.FullName);
377 Directory.CreateDirectory(Path.GetDirectoryName(destinationPath));
378 entry.ExtractToFile(destinationPath, overwrite);
383 static async Task DownloadAndExtractInsideDirectory(
string url,
string path,
string setupDir)
385 string urlName = Path.GetFileName(url);
386 string setupFile = Path.Combine(setupDir, urlName +
".complete");
387 if (File.Exists(setupFile))
return;
389 string zipPath = Path.Combine(Application.temporaryCachePath, urlName);
390 await DownloadFile(url, zipPath,
true,
null, SetLibraryProgress);
392 AssetDatabase.StartAssetEditing();
393 ExtractInsideDirectory(zipPath, path);
394 CreateEmptyFile(setupFile);
395 AssetDatabase.StopAssetEditing();
397 File.Delete(zipPath);
400 static async Task DownloadLibrary()
402 if (libraryProgress < 1)
return;
407 string setupDir = Path.Combine(
libraryPath,
"setup");
408 Directory.CreateDirectory(setupDir);
414 AssetDatabase.StartAssetEditing();
415 string androidDir = Path.Combine(
libraryPath,
"android");
416 if (Directory.Exists(androidDir))
418 string androidPluginsDir = Path.Combine(Application.dataPath,
"Plugins",
"Android");
419 Directory.CreateDirectory(androidPluginsDir);
420 string pluginDir = Path.Combine(androidPluginsDir, Path.GetFileName(
libraryPath));
421 if (Directory.Exists(pluginDir)) Directory.Delete(pluginDir,
true);
422 Directory.Move(androidDir, pluginDir);
423 if (File.Exists(androidDir +
".meta")) File.Delete(androidDir +
".meta");
425 AssetDatabase.StopAssetEditing();
438 private static void SetLibraryProgress(
float progress)
440 libraryProgress = Math.Min(0.99f, progress);
443 public static string AddAsset(
string assetPath)
445 if (!File.Exists(assetPath))
447 LogError($
"{assetPath} does not exist!");
450 string assetDir = GetAssetPath();
451 if (IsSubPath(assetPath, assetDir))
return RelativePath(assetPath, assetDir);
453 string filename = Path.GetFileName(assetPath);
454 string fullPath = GetAssetPath(filename);
455 AssetDatabase.StartAssetEditing();
456 foreach (
string path
in new string[] {fullPath, fullPath +
".meta"})
458 if (File.Exists(path)) File.Delete(path);
460 File.Copy(assetPath, fullPath);
461 AssetDatabase.StopAssetEditing();
471 errorCallbacks.Add(callback);
477 errorCallbacks.Remove(callback);
483 errorCallbacks.Clear();
486 public static int GetMaxFreqKHz(
int cpuId)
488 string[] paths =
new string[]
490 $
"/sys/devices/system/cpu/cpufreq/stats/cpu{cpuId}/time_in_state",
491 $
"/sys/devices/system/cpu/cpu{cpuId}/cpufreq/stats/time_in_state",
492 $
"/sys/devices/system/cpu/cpu{cpuId}/cpufreq/cpuinfo_max_freq"
495 foreach (var path
in paths)
497 if (!File.Exists(path))
continue;
500 using (StreamReader sr =
new StreamReader(path))
503 while ((line = sr.ReadLine()) !=
null)
505 string[] parts = line.Split(
' ');
506 if (parts.Length > 0 &&
int.TryParse(parts[0], out
int freqKHz))
508 if (freqKHz > maxFreqKHz)
510 maxFreqKHz = freqKHz;
515 if (maxFreqKHz != 0)
return maxFreqKHz;
520 public static bool IsSmtCpu(
int cpuId)
522 string[] paths =
new string[]
524 $
"/sys/devices/system/cpu/cpu{cpuId}/topology/core_cpus_list",
525 $
"/sys/devices/system/cpu/cpu{cpuId}/topology/thread_siblings_list"
528 foreach (var path
in paths)
530 if (!File.Exists(path))
continue;
531 using (StreamReader sr =
new StreamReader(path))
534 while ((line = sr.ReadLine()) !=
null)
536 if (line.Contains(
",") || line.Contains(
"-"))
552 int maxFreqKHzMin =
int.MaxValue;
553 int maxFreqKHzMax = 0;
554 List<int> cpuMaxFreqKHz =
new List<int>();
555 List<bool> cpuIsSmtCpu =
new List<bool>();
559 string cpuPath =
"/sys/devices/system/cpu/";
561 if (Directory.Exists(cpuPath))
563 foreach (
string cpuDir
in Directory.GetDirectories(cpuPath))
565 string dirName = Path.GetFileName(cpuDir);
566 if (!dirName.StartsWith(
"cpu"))
continue;
567 if (!
int.TryParse(dirName.Substring(3), out coreIndex))
continue;
569 int maxFreqKHz = GetMaxFreqKHz(coreIndex);
570 cpuMaxFreqKHz.Add(maxFreqKHz);
571 if (maxFreqKHz > maxFreqKHzMax) maxFreqKHzMax = maxFreqKHz;
572 if (maxFreqKHz < maxFreqKHzMin) maxFreqKHzMin = maxFreqKHz;
573 cpuIsSmtCpu.Add(IsSmtCpu(coreIndex));
583 int numCores = SystemInfo.processorCount;
584 int maxFreqKHzMedium = (maxFreqKHzMin + maxFreqKHzMax) / 2;
585 if (maxFreqKHzMedium == maxFreqKHzMax) numBigCores = numCores;
588 for (
int i = 0; i < cpuMaxFreqKHz.Count; i++)
590 if (cpuIsSmtCpu[i] || cpuMaxFreqKHz[i] >= maxFreqKHzMedium) numBigCores++;
594 if (numBigCores == 0) numBigCores = SystemInfo.processorCount / 2;
595 else numBigCores = Math.Min(numBigCores, SystemInfo.processorCount);
606 List<int> capacities =
new List<int>();
607 int minCapacity =
int.MaxValue;
610 string cpuPath =
"/sys/devices/system/cpu/";
612 if (Directory.Exists(cpuPath))
614 foreach (
string cpuDir
in Directory.GetDirectories(cpuPath))
616 string dirName = Path.GetFileName(cpuDir);
617 if (!dirName.StartsWith(
"cpu"))
continue;
618 if (!
int.TryParse(dirName.Substring(3), out coreIndex))
continue;
620 string capacityPath = Path.Combine(cpuDir,
"cpu_capacity");
621 if (!File.Exists(capacityPath))
break;
623 int capacity =
int.Parse(File.ReadAllText(capacityPath).Trim());
624 capacities.Add(capacity);
625 if (minCapacity > capacity) minCapacity = capacity;
635 foreach (
int capacity
in capacities)
637 if (capacity >= 2 * minCapacity) numBigCores++;
640 if (numBigCores == 0 || numBigCores > SystemInfo.processorCount) numBigCores = SystemInfo.processorCount;