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.

ChatSession.cs 1.7 kB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253
  1. using LLama.Types;
  2. using System;
  3. using System.Collections.Generic;
  4. using System.IO;
  5. using System.Text;
  6. namespace LLama
  7. {
  8. public class ChatSession<T> where T: IChatModel
  9. {
  10. IChatModel _model;
  11. List<ChatMessageRecord> History { get; } = new List<ChatMessageRecord>();
  12. public ChatSession(T model)
  13. {
  14. _model = model;
  15. }
  16. public IEnumerable<string> Chat(string text, string? prompt = null, string encoding = "UTF-8")
  17. {
  18. History.Add(new ChatMessageRecord(new ChatCompletionMessage(ChatRole.Human, text), DateTime.Now));
  19. string totalResponse = "";
  20. foreach(var response in _model.Chat(text, prompt, encoding))
  21. {
  22. totalResponse += response;
  23. yield return response;
  24. }
  25. History.Add(new ChatMessageRecord(new ChatCompletionMessage(ChatRole.Assistant, totalResponse), DateTime.Now));
  26. }
  27. public ChatSession<T> WithPrompt(string prompt, string encoding = "UTF-8")
  28. {
  29. _model.InitChatPrompt(prompt, encoding);
  30. return this;
  31. }
  32. public ChatSession<T> WithPromptFile(string promptFilename, string encoding = "UTF-8")
  33. {
  34. return WithPrompt(File.ReadAllText(promptFilename), encoding);
  35. }
  36. /// <summary>
  37. /// Set the keyword to split the return value of chat AI.
  38. /// </summary>
  39. /// <param name="humanName"></param>
  40. /// <returns></returns>
  41. public ChatSession<T> WithAntiprompt(string[] antiprompt)
  42. {
  43. _model.InitChatAntiprompt(antiprompt);
  44. return this;
  45. }
  46. }
  47. }

C#/.NET上易用的LLM高性能推理框架,支持LLaMA和LLaVA系列模型。