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

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071
  1. using System.Security.Cryptography;
  2. using System.Text;
  3. using LLama.Abstractions;
  4. using LLama.Common;
  5. namespace LLama.Examples.Examples
  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. using var weights = LLamaWeights.LoadFromFile(@params);
  16. // Create 2 contexts sharing the same weights
  17. using var aliceCtx = weights.CreateContext(@params);
  18. var alice = new InteractiveExecutor(aliceCtx);
  19. using var bobCtx = weights.CreateContext(@params);
  20. var bob = new InteractiveExecutor(bobCtx);
  21. // Initial alice prompt
  22. 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";
  23. var aliceResponse = await Prompt(alice, ConsoleColor.Green, alicePrompt, false, false);
  24. // Initial bob prompt
  25. 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}";
  26. var bobResponse = await Prompt(bob, ConsoleColor.Red, bobPrompt, true, true);
  27. // swap back and forth from Alice to Bob
  28. while (true)
  29. {
  30. aliceResponse = await Prompt(alice, ConsoleColor.Green, bobResponse, false, true);
  31. bobResponse = await Prompt(bob, ConsoleColor.Red, aliceResponse, false, true);
  32. if (Console.KeyAvailable)
  33. break;
  34. }
  35. }
  36. private static async Task<string> Prompt(ILLamaExecutor executor, ConsoleColor color, string prompt, bool showPrompt, bool showResponse)
  37. {
  38. var inferenceParams = new InferenceParams
  39. {
  40. Temperature = 0.9f,
  41. AntiPrompts = new List<string> { "Alice:", "Bob:", "User:" },
  42. MaxTokens = 128,
  43. Mirostat = MirostatType.Mirostat2,
  44. MirostatTau = 10,
  45. };
  46. Console.ForegroundColor = ConsoleColor.White;
  47. if (showPrompt)
  48. Console.Write(prompt);
  49. Console.ForegroundColor = color;
  50. var builder = new StringBuilder();
  51. await foreach (var text in executor.InferAsync(prompt, inferenceParams))
  52. {
  53. builder.Append(text);
  54. if (showResponse)
  55. Console.Write(text);
  56. }
  57. return builder.ToString();
  58. }
  59. }
  60. }