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.

StatefulChatService.cs 2.7 kB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293
  1. 
  2. using LLama.WebAPI.Models;
  3. using Microsoft;
  4. using System.Runtime.CompilerServices;
  5. namespace LLama.WebAPI.Services;
  6. public class StatefulChatService : IDisposable
  7. {
  8. private readonly ChatSession _session;
  9. private readonly LLamaContext _context;
  10. private bool _continue = false;
  11. private const string SystemPrompt = "Transcript of a dialog, where the User interacts with an Assistant. Assistant is helpful, kind, honest, good at writing, and never fails to answer the User's requests immediately and with precision.";
  12. public StatefulChatService(IConfiguration configuration)
  13. {
  14. var @params = new Common.ModelParams(configuration["ModelPath"])
  15. {
  16. ContextSize = 512,
  17. };
  18. // todo: share weights from a central service
  19. using var weights = LLamaWeights.LoadFromFile(@params);
  20. _context = new LLamaContext(weights, @params);
  21. _session = new ChatSession(new InteractiveExecutor(_context));
  22. _session.History.AddMessage(Common.AuthorRole.System, SystemPrompt);
  23. }
  24. public void Dispose()
  25. {
  26. _context?.Dispose();
  27. }
  28. public async Task<string> Send(SendMessageInput input)
  29. {
  30. if (!_continue)
  31. {
  32. Console.Write(SystemPrompt);
  33. _continue = true;
  34. }
  35. Console.ForegroundColor = ConsoleColor.Green;
  36. Console.Write(input.Text);
  37. Console.ForegroundColor = ConsoleColor.White;
  38. var outputs = _session.ChatAsync(
  39. new Common.ChatHistory.Message(Common.AuthorRole.User, input.Text),
  40. new Common.InferenceParams()
  41. {
  42. RepeatPenalty = 1.0f,
  43. AntiPrompts = new string[] { "User:" },
  44. });
  45. var result = "";
  46. await foreach (var output in outputs)
  47. {
  48. Console.Write(output);
  49. result += output;
  50. }
  51. return result;
  52. }
  53. public async IAsyncEnumerable<string> SendStream(SendMessageInput input)
  54. {
  55. if (!_continue)
  56. {
  57. Console.Write(SystemPrompt);
  58. _continue = true;
  59. }
  60. Console.ForegroundColor = ConsoleColor.Green;
  61. Console.Write(input.Text);
  62. Console.ForegroundColor = ConsoleColor.White;
  63. var outputs = _session.ChatAsync(
  64. new Common.ChatHistory.Message(Common.AuthorRole.User, input.Text)
  65. , new Common.InferenceParams()
  66. {
  67. RepeatPenalty = 1.0f,
  68. AntiPrompts = new string[] { "User:" },
  69. });
  70. await foreach (var output in outputs)
  71. {
  72. Console.Write(output);
  73. yield return output;
  74. }
  75. }
  76. }