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 3.2 kB

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