You can not select more than 25 topics Topics must start with a chinese character,a letter or number, can include dashes ('-') and can be up to 35 characters long.

LoadAndSaveSession.cs 2.9 kB

2 years ago
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869
  1. using LLama.Common;
  2. namespace LLama.Examples.Examples
  3. {
  4. public class SaveAndLoadSession
  5. {
  6. public static async Task Run()
  7. {
  8. Console.Write("Please input your model path: ");
  9. var modelPath = Console.ReadLine();
  10. var prompt = (await File.ReadAllTextAsync("Assets/chat-with-bob.txt")).Trim();
  11. var parameters = new ModelParams(modelPath)
  12. {
  13. ContextSize = 1024,
  14. Seed = 1337,
  15. GpuLayerCount = 5
  16. };
  17. using var model = LLamaWeights.LoadFromFile(parameters);
  18. using var context = model.CreateContext(parameters);
  19. var ex = new InteractiveExecutor(context);
  20. var session = new ChatSession(ex);
  21. Console.ForegroundColor = ConsoleColor.Yellow;
  22. Console.WriteLine("The chat session has started. In this example, the prompt is printed for better visual result. Input \"save\" to save and reload the session.");
  23. Console.ForegroundColor = ConsoleColor.White;
  24. // show the prompt
  25. Console.Write(prompt);
  26. while (true)
  27. {
  28. await foreach (var text in session.ChatAsync(prompt, new InferenceParams() { Temperature = 0.6f, AntiPrompts = new List<string> { "User:" } }))
  29. {
  30. Console.Write(text);
  31. }
  32. Console.ForegroundColor = ConsoleColor.Green;
  33. prompt = Console.ReadLine();
  34. Console.ForegroundColor = ConsoleColor.White;
  35. if (prompt == "save")
  36. {
  37. Console.Write("Preparing to save the state, please input the path you want to save it: ");
  38. Console.ForegroundColor = ConsoleColor.Green;
  39. var statePath = Console.ReadLine();
  40. session.SaveSession(statePath);
  41. Console.ForegroundColor = ConsoleColor.White;
  42. Console.ForegroundColor = ConsoleColor.Yellow;
  43. Console.WriteLine("Saved session!");
  44. Console.ForegroundColor = ConsoleColor.White;
  45. ex.Context.Dispose();
  46. ex = new(new LLamaContext(model, parameters));
  47. session = new ChatSession(ex);
  48. session.LoadSession(statePath);
  49. Console.ForegroundColor = ConsoleColor.Yellow;
  50. Console.WriteLine("Loaded session!");
  51. Console.ForegroundColor = ConsoleColor.White;
  52. Console.Write("Now you can continue your session: ");
  53. Console.ForegroundColor = ConsoleColor.Green;
  54. prompt = Console.ReadLine();
  55. Console.ForegroundColor = ConsoleColor.White;
  56. }
  57. }
  58. }
  59. }
  60. }