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

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