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

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051
  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 LLamaContext _context;
  10. private readonly ChatSession _session;
  11. public StatelessChatService(IConfiguration configuration)
  12. {
  13. _context = new LLamaContext(new ModelParams(configuration["ModelPath"])
  14. {
  15. ContextSize = 512,
  16. });
  17. // TODO: replace with a stateless executor
  18. _session = new ChatSession(new InteractiveExecutor(_context))
  19. .WithOutputTransform(new LLamaTransforms.KeywordTextOutputStreamTransform(new string[] { "User:", "Assistant:" }, redundancyLength: 8))
  20. .WithHistoryTransform(new HistoryTransform());
  21. }
  22. public async Task<string> SendAsync(ChatHistory history)
  23. {
  24. var result = _session.ChatAsync(history, new InferenceParams()
  25. {
  26. AntiPrompts = new string[] { "User:" },
  27. });
  28. var sb = new StringBuilder();
  29. await foreach (var r in result)
  30. {
  31. Console.Write(r);
  32. sb.Append(r);
  33. }
  34. return sb.ToString();
  35. }
  36. }
  37. public class HistoryTransform : DefaultHistoryTransform
  38. {
  39. public override string HistoryToText(ChatHistory history)
  40. {
  41. return base.HistoryToText(history) + "\n Assistant:";
  42. }
  43. }
  44. }