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
12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576
  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. Seed = 1337,
  13. GpuLayerCount = 5
  14. };
  15. using var model = await LLamaWeights.LoadFromFileAsync(parameters);
  16. using var context = model.CreateContext(parameters);
  17. var ex = new InteractiveExecutor(context);
  18. var session = new ChatSession(ex);
  19. Console.ForegroundColor = ConsoleColor.Yellow;
  20. 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.");
  21. Console.ForegroundColor = ConsoleColor.White;
  22. // show the prompt
  23. Console.Write(prompt);
  24. while (true)
  25. {
  26. await foreach (
  27. var text
  28. in session.ChatAsync(
  29. new ChatHistory.Message(AuthorRole.User, prompt),
  30. new InferenceParams()
  31. {
  32. Temperature = 0.6f,
  33. AntiPrompts = new List<string> { "User:" }
  34. }))
  35. {
  36. Console.Write(text);
  37. }
  38. Console.ForegroundColor = ConsoleColor.Green;
  39. prompt = Console.ReadLine();
  40. Console.ForegroundColor = ConsoleColor.White;
  41. if (prompt == "save")
  42. {
  43. Console.Write("Preparing to save the state, please input the path you want to save it: ");
  44. Console.ForegroundColor = ConsoleColor.Green;
  45. var statePath = Console.ReadLine();
  46. session.SaveSession(statePath);
  47. Console.ForegroundColor = ConsoleColor.White;
  48. Console.ForegroundColor = ConsoleColor.Yellow;
  49. Console.WriteLine("Saved session!");
  50. Console.ForegroundColor = ConsoleColor.White;
  51. ex.Context.Dispose();
  52. ex = new(new LLamaContext(model, parameters));
  53. session = new ChatSession(ex);
  54. session.LoadSession(statePath);
  55. Console.ForegroundColor = ConsoleColor.Yellow;
  56. Console.WriteLine("Loaded session!");
  57. Console.ForegroundColor = ConsoleColor.White;
  58. Console.Write("Now you can continue your session: ");
  59. Console.ForegroundColor = ConsoleColor.Green;
  60. prompt = Console.ReadLine();
  61. Console.ForegroundColor = ConsoleColor.White;
  62. }
  63. }
  64. }
  65. }
  66. }