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.

ModelSessionService.cs 8.7 kB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205
  1. using LLama.Web.Async;
  2. using LLama.Web.Common;
  3. using LLama.Web.Models;
  4. using System.Collections.Concurrent;
  5. using System.Diagnostics;
  6. using System.Runtime.CompilerServices;
  7. namespace LLama.Web.Services;
  8. /// <summary>
  9. /// Example Service for handling a model session for a websockets connection lifetime
  10. /// Each websocket connection will create its own unique session and context allowing you to use multiple tabs to compare prompts etc
  11. /// </summary>
  12. public class ModelSessionService : IModelSessionService
  13. {
  14. private readonly AsyncGuard<string> _sessionGuard;
  15. private readonly IModelService _modelService;
  16. private readonly ConcurrentDictionary<string, ModelSession> _modelSessions;
  17. /// <summary>
  18. /// Initializes a new instance of the <see cref="ModelSessionService{T}"/> class.
  19. /// </summary>
  20. /// <param name="modelService">The model service.</param>
  21. /// <param name="modelSessionStateService">The model session state service.</param>
  22. public ModelSessionService(IModelService modelService)
  23. {
  24. _modelService = modelService;
  25. _sessionGuard = new AsyncGuard<string>();
  26. _modelSessions = new ConcurrentDictionary<string, ModelSession>();
  27. }
  28. /// <summary>
  29. /// Gets the ModelSession with the specified Id.
  30. /// </summary>
  31. /// <param name="sessionId">The session identifier.</param>
  32. /// <returns>The ModelSession if exists, otherwise null</returns>
  33. public Task<ModelSession> GetAsync(string sessionId)
  34. {
  35. return Task.FromResult(_modelSessions.TryGetValue(sessionId, out var session) ? session : null);
  36. }
  37. /// <summary>
  38. /// Gets all ModelSessions
  39. /// </summary>
  40. /// <returns>A collection oa all Model instances</returns>
  41. public Task<IEnumerable<ModelSession>> GetAllAsync()
  42. {
  43. return Task.FromResult<IEnumerable<ModelSession>>(_modelSessions.Values);
  44. }
  45. /// <summary>
  46. /// Creates a new ModelSession
  47. /// </summary>
  48. /// <param name="sessionId">The session identifier.</param>
  49. /// <param name="sessionConfig">The session configuration.</param>
  50. /// <param name="inferenceConfig">The default inference configuration, will be used for all inference where no infer configuration is supplied.</param>
  51. /// <param name="cancellationToken">The cancellation token.</param>
  52. /// <returns></returns>
  53. /// <exception cref="System.Exception">
  54. /// Session with id {sessionId} already exists
  55. /// or
  56. /// Failed to create model session
  57. /// </exception>
  58. public async Task<ModelSession> CreateAsync(string sessionId, ISessionConfig sessionConfig, InferenceOptions inferenceConfig = null, CancellationToken cancellationToken = default)
  59. {
  60. if (_modelSessions.TryGetValue(sessionId, out _))
  61. throw new Exception($"Session with id {sessionId} already exists");
  62. // Create context
  63. var (model, context) = await _modelService.GetOrCreateModelAndContext(sessionConfig.Model, sessionId);
  64. // Create session
  65. var modelSession = new ModelSession(model, context, sessionId, sessionConfig, inferenceConfig);
  66. if (!_modelSessions.TryAdd(sessionId, modelSession))
  67. throw new Exception($"Failed to create model session");
  68. // Run initial Prompt
  69. await modelSession.InitializePrompt(inferenceConfig, cancellationToken);
  70. return modelSession;
  71. }
  72. /// <summary>
  73. /// Closes the session
  74. /// </summary>
  75. /// <param name="sessionId">The session identifier.</param>
  76. /// <returns></returns>
  77. public async Task<bool> CloseAsync(string sessionId)
  78. {
  79. if (_modelSessions.TryRemove(sessionId, out var modelSession))
  80. {
  81. modelSession.CancelInfer();
  82. return await _modelService.RemoveContext(modelSession.ModelName, sessionId);
  83. }
  84. return false;
  85. }
  86. /// <summary>
  87. /// Runs inference on the current ModelSession
  88. /// </summary>
  89. /// <param name="sessionId">The session identifier.</param>
  90. /// <param name="prompt">The prompt.</param>
  91. /// <param name="inferenceConfig">The inference configuration, if null session default is used</param>
  92. /// <param name="cancellationToken">The cancellation token.</param>
  93. /// <exception cref="System.Exception">Inference is already running for this session</exception>
  94. public async IAsyncEnumerable<TokenModel> InferAsync(string sessionId, string prompt, InferenceOptions inferenceConfig = null, [EnumeratorCancellation] CancellationToken cancellationToken = default)
  95. {
  96. if (!_sessionGuard.Guard(sessionId))
  97. throw new Exception($"Inference is already running for this session");
  98. try
  99. {
  100. if (!_modelSessions.TryGetValue(sessionId, out var modelSession))
  101. yield break;
  102. // Send begin of response
  103. var stopwatch = Stopwatch.GetTimestamp();
  104. yield return new TokenModel(default, default, TokenType.Begin);
  105. // Send content of response
  106. await foreach (var token in modelSession.InferAsync(prompt, inferenceConfig, cancellationToken).ConfigureAwait(false))
  107. {
  108. yield return new TokenModel(default, token);
  109. }
  110. // Send end of response
  111. var elapsedTime = GetElapsed(stopwatch);
  112. var endTokenType = modelSession.IsInferCanceled() ? TokenType.Cancel : TokenType.End;
  113. var signature = endTokenType == TokenType.Cancel
  114. ? $"Cancelled after {elapsedTime / 1000:F0} seconds"
  115. : $"Completed in {elapsedTime / 1000:F0} seconds";
  116. yield return new TokenModel(default, signature, endTokenType);
  117. }
  118. finally
  119. {
  120. _sessionGuard.Release(sessionId);
  121. }
  122. }
  123. /// <summary>
  124. /// Runs inference on the current ModelSession
  125. /// </summary>
  126. /// <param name="sessionId">The session identifier.</param>
  127. /// <param name="prompt">The prompt.</param>
  128. /// <param name="inferenceConfig">The inference configuration, if null session default is used</param>
  129. /// <param name="cancellationToken">The cancellation token.</param>
  130. /// <returns>Streaming async result of <see cref="System.String" /></returns>
  131. /// <exception cref="System.Exception">Inference is already running for this session</exception>
  132. public IAsyncEnumerable<string> InferTextAsync(string sessionId, string prompt, InferenceOptions inferenceConfig = null, CancellationToken cancellationToken = default)
  133. {
  134. async IAsyncEnumerable<string> InferTextInternal()
  135. {
  136. await foreach (var token in InferAsync(sessionId, prompt, inferenceConfig, cancellationToken).ConfigureAwait(false))
  137. {
  138. if (token.TokenType == TokenType.Content)
  139. yield return token.Content;
  140. }
  141. }
  142. return InferTextInternal();
  143. }
  144. /// <summary>
  145. /// Runs inference on the current ModelSession
  146. /// </summary>
  147. /// <param name="sessionId">The session identifier.</param>
  148. /// <param name="prompt">The prompt.</param>
  149. /// <param name="inferenceConfig">The inference configuration, if null session default is used</param>
  150. /// <param name="cancellationToken">The cancellation token.</param>
  151. /// <returns>Completed inference result as string</returns>
  152. /// <exception cref="System.Exception">Inference is already running for this session</exception>
  153. public async Task<string> InferTextCompleteAsync(string sessionId, string prompt, InferenceOptions inferenceConfig = null, CancellationToken cancellationToken = default)
  154. {
  155. var inferResult = await InferAsync(sessionId, prompt, inferenceConfig, cancellationToken)
  156. .Where(x => x.TokenType == TokenType.Content)
  157. .Select(x => x.Content)
  158. .ToListAsync(cancellationToken: cancellationToken);
  159. return string.Concat(inferResult);
  160. }
  161. /// <summary>
  162. /// Cancels the current inference action.
  163. /// </summary>
  164. /// <param name="sessionId">The session identifier.</param>
  165. /// <returns></returns>
  166. public Task<bool> CancelAsync(string sessionId)
  167. {
  168. if (_modelSessions.TryGetValue(sessionId, out var modelSession))
  169. {
  170. modelSession.CancelInfer();
  171. return Task.FromResult(true);
  172. }
  173. return Task.FromResult(false);
  174. }
  175. /// <summary>
  176. /// Gets the elapsed time in milliseconds.
  177. /// </summary>
  178. /// <param name="timestamp">The timestamp.</param>
  179. /// <returns></returns>
  180. private static int GetElapsed(long timestamp)
  181. {
  182. return (int)Stopwatch.GetElapsedTime(timestamp).TotalMilliseconds;
  183. }
  184. }