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.

StatelessChatService.cs 1.5 kB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748
  1. using LLama.Common;
  2. using Microsoft.AspNetCore.Http;
  3. using System.Text;
  4. using static LLama.LLamaTransforms;
  5. namespace LLama.WebAPI.Services
  6. {
  7. public class StatelessChatService
  8. {
  9. private readonly LLamaModel _model;
  10. private readonly ChatSession _session;
  11. public StatelessChatService(IConfiguration configuration)
  12. {
  13. _model = new LLamaModel(new ModelParams(configuration["ModelPath"], contextSize: 512));
  14. // TODO: replace with a stateless executor
  15. _session = new ChatSession(new InteractiveExecutor(_model))
  16. .WithOutputTransform(new LLamaTransforms.KeywordTextOutputStreamTransform(new string[] { "User:", "Assistant:" }, redundancyLength: 8))
  17. .WithHistoryTransform(new HistoryTransform());
  18. }
  19. public async Task<string> SendAsync(ChatHistory history)
  20. {
  21. var result = _session.ChatAsync(history, new InferenceParams()
  22. {
  23. AntiPrompts = new string[] { "User:" },
  24. });
  25. var sb = new StringBuilder();
  26. await foreach (var r in result)
  27. {
  28. Console.Write(r);
  29. sb.Append(r);
  30. }
  31. return sb.ToString();
  32. }
  33. }
  34. public class HistoryTransform : DefaultHistoryTransform
  35. {
  36. public override string HistoryToText(ChatHistory history)
  37. {
  38. return base.HistoryToText(history) + "\n Assistant:";
  39. }
  40. }
  41. }