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

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990
  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.\n\n"
  12. + "User: ";
  13. public StatefulChatService(IConfiguration configuration)
  14. {
  15. var @params = new Common.ModelParams(configuration["ModelPath"])
  16. {
  17. ContextSize = 512,
  18. };
  19. // todo: share weights from a central service
  20. using var weights = LLamaWeights.LoadFromFile(@params);
  21. _context = new LLamaContext(weights, @params);
  22. _session = new ChatSession(new InteractiveExecutor(_context));
  23. }
  24. public void Dispose()
  25. {
  26. _context?.Dispose();
  27. }
  28. public async Task<string> Send(SendMessageInput input)
  29. {
  30. var userInput = input.Text;
  31. if (!_continue)
  32. {
  33. userInput = SystemPrompt + userInput;
  34. Console.Write(SystemPrompt);
  35. _continue = true;
  36. }
  37. Console.ForegroundColor = ConsoleColor.Green;
  38. Console.Write(input.Text);
  39. Console.ForegroundColor = ConsoleColor.White;
  40. var outputs = _session.ChatAsync(userInput, 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. var userInput = input.Text;
  56. if (!_continue)
  57. {
  58. userInput = SystemPrompt + userInput;
  59. Console.Write(SystemPrompt);
  60. _continue = true;
  61. }
  62. Console.ForegroundColor = ConsoleColor.Green;
  63. Console.Write(input.Text);
  64. Console.ForegroundColor = ConsoleColor.White;
  65. var outputs = _session.ChatAsync(userInput, 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. }