ChatResponseExtensions.cs 1.9 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071
  1. // Models/ChatResponseExtensions.cs
  2. namespace OASystem.API.OAMethodLib.TokenHubAI.Models;
  3. /// <summary>
  4. /// ChatResponse 扩展方法
  5. /// </summary>
  6. public static class ChatResponseExtensions
  7. {
  8. /// <summary>
  9. /// 获取第一个选择的消息内容
  10. /// </summary>
  11. public static string? GetFirstContent(this ChatResponse response)
  12. {
  13. if (response.Choices != null && response.Choices.Count > 0)
  14. {
  15. var choice = response.Choices[0];
  16. return choice.Message?.Content ?? choice.Delta?.Content;
  17. }
  18. return response.Content;
  19. }
  20. /// <summary>
  21. /// 获取完成原因
  22. /// </summary>
  23. public static string? GetFinishReason(this ChatResponse response)
  24. {
  25. if (response.Choices != null && response.Choices.Count > 0)
  26. {
  27. return response.Choices[0].FinishReason;
  28. }
  29. return response.FinishReason;
  30. }
  31. /// <summary>
  32. /// 是否正常结束
  33. /// </summary>
  34. public static bool IsNormalEnd(this ChatResponse response)
  35. {
  36. var reason = response.GetFinishReason();
  37. return reason is null or "stop";
  38. }
  39. /// <summary>
  40. /// 是否被内容过滤
  41. /// </summary>
  42. public static bool IsContentFiltered(this ChatResponse response)
  43. {
  44. return response.GetFinishReason() == "content_filter";
  45. }
  46. /// <summary>
  47. /// 是否达到长度限制
  48. /// </summary>
  49. public static bool IsLengthLimit(this ChatResponse response)
  50. {
  51. return response.GetFinishReason() == "length";
  52. }
  53. ///// <summary>
  54. ///// 获取工具调用列表
  55. ///// </summary>
  56. //public static List<ToolCall>? GetToolCalls(this ChatResponse response)
  57. //{
  58. // if (response.Choices != null && response.Choices.Count > 0)
  59. // {
  60. // var message = response.Choices[0].Message;
  61. // return message?.ToolCalls;
  62. // }
  63. // return response.ToolCalls;
  64. //}
  65. }