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

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485
  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. _context = new LLamaContext(new Common.ModelParams(configuration["ModelPath"])
  16. {
  17. ContextSize = 512
  18. });
  19. _session = new ChatSession(new InteractiveExecutor(_context));
  20. }
  21. public void Dispose()
  22. {
  23. _context?.Dispose();
  24. }
  25. public async Task<string> Send(SendMessageInput input)
  26. {
  27. var userInput = input.Text;
  28. if (!_continue)
  29. {
  30. userInput = SystemPrompt + userInput;
  31. Console.Write(SystemPrompt);
  32. _continue = true;
  33. }
  34. Console.ForegroundColor = ConsoleColor.Green;
  35. Console.Write(input.Text);
  36. Console.ForegroundColor = ConsoleColor.White;
  37. var outputs = _session.ChatAsync(userInput, new Common.InferenceParams()
  38. {
  39. RepeatPenalty = 1.0f,
  40. AntiPrompts = new string[] { "User:" },
  41. });
  42. var result = "";
  43. await foreach (var output in outputs)
  44. {
  45. Console.Write(output);
  46. result += output;
  47. }
  48. return result;
  49. }
  50. public async IAsyncEnumerable<string> SendStream(SendMessageInput input)
  51. {
  52. var userInput = input.Text;
  53. if (!_continue)
  54. {
  55. userInput = SystemPrompt + userInput;
  56. Console.Write(SystemPrompt);
  57. _continue = true;
  58. }
  59. Console.ForegroundColor = ConsoleColor.Green;
  60. Console.Write(input.Text);
  61. Console.ForegroundColor = ConsoleColor.White;
  62. var outputs = _session.ChatAsync(userInput, new Common.InferenceParams()
  63. {
  64. RepeatPenalty = 1.0f,
  65. AntiPrompts = new string[] { "User:" },
  66. });
  67. await foreach (var output in outputs)
  68. {
  69. Console.Write(output);
  70. yield return output;
  71. }
  72. }
  73. }