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.

TalkToYourself.cs 2.9 kB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374
  1. using System.Security.Cryptography;
  2. using System.Text;
  3. using LLama.Abstractions;
  4. using LLama.Common;
  5. namespace LLama.Examples.NewVersion
  6. {
  7. public class TalkToYourself
  8. {
  9. public static async Task Run()
  10. {
  11. Console.Write("Please input your model path: ");
  12. var modelPath = Console.ReadLine();
  13. // Load weights into memory
  14. var @params = new ModelParams(modelPath)
  15. {
  16. Seed = RandomNumberGenerator.GetInt32(int.MaxValue)
  17. };
  18. using var weights = LLamaWeights.LoadFromFile(@params);
  19. // Create 2 contexts sharing the same weights
  20. using var aliceCtx = weights.CreateContext(@params);
  21. var alice = new InteractiveExecutor(aliceCtx);
  22. using var bobCtx = weights.CreateContext(@params);
  23. var bob = new InteractiveExecutor(bobCtx);
  24. // Initial alice prompt
  25. var alicePrompt = "Transcript of a dialog, where the Alice interacts a person named Bob. Alice is friendly, kind, honest and good at writing.\nAlice: Hello";
  26. var aliceResponse = await Prompt(alice, ConsoleColor.Green, alicePrompt, false, false);
  27. // Initial bob prompt
  28. var bobPrompt = $"Transcript of a dialog, where the Bob interacts a person named Alice. Bob is smart, intellectual and good at writing.\nAlice: Hello{aliceResponse}";
  29. var bobResponse = await Prompt(bob, ConsoleColor.Red, bobPrompt, true, true);
  30. // swap back and forth from Alice to Bob
  31. while (true)
  32. {
  33. aliceResponse = await Prompt(alice, ConsoleColor.Green, bobResponse, false, true);
  34. bobResponse = await Prompt(bob, ConsoleColor.Red, aliceResponse, false, true);
  35. if (Console.KeyAvailable)
  36. break;
  37. }
  38. }
  39. private static async Task<string> Prompt(ILLamaExecutor executor, ConsoleColor color, string prompt, bool showPrompt, bool showResponse)
  40. {
  41. var inferenceParams = new InferenceParams
  42. {
  43. Temperature = 0.9f,
  44. AntiPrompts = new List<string> { "Alice:", "Bob:", "User:" },
  45. MaxTokens = 128,
  46. Mirostat = MirostatType.Mirostat2,
  47. MirostatTau = 10,
  48. };
  49. Console.ForegroundColor = ConsoleColor.White;
  50. if (showPrompt)
  51. Console.Write(prompt);
  52. Console.ForegroundColor = color;
  53. var builder = new StringBuilder();
  54. await foreach (var text in executor.InferAsync(prompt, inferenceParams))
  55. {
  56. builder.Append(text);
  57. if (showResponse)
  58. Console.Write(text);
  59. }
  60. return builder.ToString();
  61. }
  62. }
  63. }