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

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