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.1 kB

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