workflow_statistic.py 10 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279
  1. from datetime import datetime
  2. from decimal import Decimal
  3. import pytz
  4. from flask import jsonify
  5. from flask_login import current_user
  6. from flask_restful import Resource, reqparse
  7. from controllers.console import api
  8. from controllers.console.app.wraps import get_app_model
  9. from controllers.console.setup import setup_required
  10. from controllers.console.wraps import account_initialization_required
  11. from extensions.ext_database import db
  12. from libs.helper import datetime_string
  13. from libs.login import login_required
  14. from models.model import AppMode
  15. from models.workflow import WorkflowRunTriggeredFrom
  16. class WorkflowDailyRunsStatistic(Resource):
  17. @setup_required
  18. @login_required
  19. @account_initialization_required
  20. @get_app_model
  21. def get(self, app_model):
  22. account = current_user
  23. parser = reqparse.RequestParser()
  24. parser.add_argument('start', type=datetime_string('%Y-%m-%d %H:%M'), location='args')
  25. parser.add_argument('end', type=datetime_string('%Y-%m-%d %H:%M'), location='args')
  26. args = parser.parse_args()
  27. sql_query = '''
  28. SELECT date(DATE_TRUNC('day', created_at AT TIME ZONE 'UTC' AT TIME ZONE :tz )) AS date, count(id) AS runs
  29. FROM workflow_runs
  30. WHERE app_id = :app_id
  31. AND triggered_from = :triggered_from
  32. '''
  33. arg_dict = {'tz': account.timezone, 'app_id': app_model.id, 'triggered_from': WorkflowRunTriggeredFrom.APP_RUN.value}
  34. timezone = pytz.timezone(account.timezone)
  35. utc_timezone = pytz.utc
  36. if args['start']:
  37. start_datetime = datetime.strptime(args['start'], '%Y-%m-%d %H:%M')
  38. start_datetime = start_datetime.replace(second=0)
  39. start_datetime_timezone = timezone.localize(start_datetime)
  40. start_datetime_utc = start_datetime_timezone.astimezone(utc_timezone)
  41. sql_query += ' and created_at >= :start'
  42. arg_dict['start'] = start_datetime_utc
  43. if args['end']:
  44. end_datetime = datetime.strptime(args['end'], '%Y-%m-%d %H:%M')
  45. end_datetime = end_datetime.replace(second=0)
  46. end_datetime_timezone = timezone.localize(end_datetime)
  47. end_datetime_utc = end_datetime_timezone.astimezone(utc_timezone)
  48. sql_query += ' and created_at < :end'
  49. arg_dict['end'] = end_datetime_utc
  50. sql_query += ' GROUP BY date order by date'
  51. response_data = []
  52. with db.engine.begin() as conn:
  53. rs = conn.execute(db.text(sql_query), arg_dict)
  54. for i in rs:
  55. response_data.append({
  56. 'date': str(i.date),
  57. 'runs': i.runs
  58. })
  59. return jsonify({
  60. 'data': response_data
  61. })
  62. class WorkflowDailyTerminalsStatistic(Resource):
  63. @setup_required
  64. @login_required
  65. @account_initialization_required
  66. @get_app_model
  67. def get(self, app_model):
  68. account = current_user
  69. parser = reqparse.RequestParser()
  70. parser.add_argument('start', type=datetime_string('%Y-%m-%d %H:%M'), location='args')
  71. parser.add_argument('end', type=datetime_string('%Y-%m-%d %H:%M'), location='args')
  72. args = parser.parse_args()
  73. sql_query = '''
  74. SELECT date(DATE_TRUNC('day', created_at AT TIME ZONE 'UTC' AT TIME ZONE :tz )) AS date, count(distinct workflow_runs.created_by) AS terminal_count
  75. FROM workflow_runs
  76. WHERE app_id = :app_id
  77. AND triggered_from = :triggered_from
  78. '''
  79. arg_dict = {'tz': account.timezone, 'app_id': app_model.id, 'triggered_from': WorkflowRunTriggeredFrom.APP_RUN.value}
  80. timezone = pytz.timezone(account.timezone)
  81. utc_timezone = pytz.utc
  82. if args['start']:
  83. start_datetime = datetime.strptime(args['start'], '%Y-%m-%d %H:%M')
  84. start_datetime = start_datetime.replace(second=0)
  85. start_datetime_timezone = timezone.localize(start_datetime)
  86. start_datetime_utc = start_datetime_timezone.astimezone(utc_timezone)
  87. sql_query += ' and created_at >= :start'
  88. arg_dict['start'] = start_datetime_utc
  89. if args['end']:
  90. end_datetime = datetime.strptime(args['end'], '%Y-%m-%d %H:%M')
  91. end_datetime = end_datetime.replace(second=0)
  92. end_datetime_timezone = timezone.localize(end_datetime)
  93. end_datetime_utc = end_datetime_timezone.astimezone(utc_timezone)
  94. sql_query += ' and created_at < :end'
  95. arg_dict['end'] = end_datetime_utc
  96. sql_query += ' GROUP BY date order by date'
  97. response_data = []
  98. with db.engine.begin() as conn:
  99. rs = conn.execute(db.text(sql_query), arg_dict)
  100. for i in rs:
  101. response_data.append({
  102. 'date': str(i.date),
  103. 'terminal_count': i.terminal_count
  104. })
  105. return jsonify({
  106. 'data': response_data
  107. })
  108. class WorkflowDailyTokenCostStatistic(Resource):
  109. @setup_required
  110. @login_required
  111. @account_initialization_required
  112. @get_app_model
  113. def get(self, app_model):
  114. account = current_user
  115. parser = reqparse.RequestParser()
  116. parser.add_argument('start', type=datetime_string('%Y-%m-%d %H:%M'), location='args')
  117. parser.add_argument('end', type=datetime_string('%Y-%m-%d %H:%M'), location='args')
  118. args = parser.parse_args()
  119. sql_query = '''
  120. SELECT
  121. date(DATE_TRUNC('day', created_at AT TIME ZONE 'UTC' AT TIME ZONE :tz )) AS date,
  122. SUM(workflow_runs.total_tokens) as token_count
  123. FROM workflow_runs
  124. WHERE app_id = :app_id
  125. AND triggered_from = :triggered_from
  126. '''
  127. arg_dict = {'tz': account.timezone, 'app_id': app_model.id, 'triggered_from': WorkflowRunTriggeredFrom.APP_RUN.value}
  128. timezone = pytz.timezone(account.timezone)
  129. utc_timezone = pytz.utc
  130. if args['start']:
  131. start_datetime = datetime.strptime(args['start'], '%Y-%m-%d %H:%M')
  132. start_datetime = start_datetime.replace(second=0)
  133. start_datetime_timezone = timezone.localize(start_datetime)
  134. start_datetime_utc = start_datetime_timezone.astimezone(utc_timezone)
  135. sql_query += ' and created_at >= :start'
  136. arg_dict['start'] = start_datetime_utc
  137. if args['end']:
  138. end_datetime = datetime.strptime(args['end'], '%Y-%m-%d %H:%M')
  139. end_datetime = end_datetime.replace(second=0)
  140. end_datetime_timezone = timezone.localize(end_datetime)
  141. end_datetime_utc = end_datetime_timezone.astimezone(utc_timezone)
  142. sql_query += ' and created_at < :end'
  143. arg_dict['end'] = end_datetime_utc
  144. sql_query += ' GROUP BY date order by date'
  145. response_data = []
  146. with db.engine.begin() as conn:
  147. rs = conn.execute(db.text(sql_query), arg_dict)
  148. for i in rs:
  149. response_data.append({
  150. 'date': str(i.date),
  151. 'token_count': i.token_count,
  152. })
  153. return jsonify({
  154. 'data': response_data
  155. })
  156. class WorkflowAverageAppInteractionStatistic(Resource):
  157. @setup_required
  158. @login_required
  159. @account_initialization_required
  160. @get_app_model(mode=[AppMode.WORKFLOW])
  161. def get(self, app_model):
  162. account = current_user
  163. parser = reqparse.RequestParser()
  164. parser.add_argument('start', type=datetime_string('%Y-%m-%d %H:%M'), location='args')
  165. parser.add_argument('end', type=datetime_string('%Y-%m-%d %H:%M'), location='args')
  166. args = parser.parse_args()
  167. sql_query = """
  168. SELECT
  169. AVG(sub.interactions) as interactions,
  170. sub.date
  171. FROM
  172. (SELECT
  173. date(DATE_TRUNC('day', c.created_at AT TIME ZONE 'UTC' AT TIME ZONE :tz )) AS date,
  174. c.created_by,
  175. COUNT(c.id) AS interactions
  176. FROM workflow_runs c
  177. WHERE c.app_id = :app_id
  178. AND c.triggered_from = :triggered_from
  179. {{start}}
  180. {{end}}
  181. GROUP BY date, c.created_by) sub
  182. GROUP BY sub.date
  183. """
  184. arg_dict = {'tz': account.timezone, 'app_id': app_model.id, 'triggered_from': WorkflowRunTriggeredFrom.APP_RUN.value}
  185. timezone = pytz.timezone(account.timezone)
  186. utc_timezone = pytz.utc
  187. if args['start']:
  188. start_datetime = datetime.strptime(args['start'], '%Y-%m-%d %H:%M')
  189. start_datetime = start_datetime.replace(second=0)
  190. start_datetime_timezone = timezone.localize(start_datetime)
  191. start_datetime_utc = start_datetime_timezone.astimezone(utc_timezone)
  192. sql_query = sql_query.replace('{{start}}', ' AND c.created_at >= :start')
  193. arg_dict['start'] = start_datetime_utc
  194. else:
  195. sql_query = sql_query.replace('{{start}}', '')
  196. if args['end']:
  197. end_datetime = datetime.strptime(args['end'], '%Y-%m-%d %H:%M')
  198. end_datetime = end_datetime.replace(second=0)
  199. end_datetime_timezone = timezone.localize(end_datetime)
  200. end_datetime_utc = end_datetime_timezone.astimezone(utc_timezone)
  201. sql_query = sql_query.replace('{{end}}', ' and c.created_at < :end')
  202. arg_dict['end'] = end_datetime_utc
  203. else:
  204. sql_query = sql_query.replace('{{end}}', '')
  205. response_data = []
  206. with db.engine.begin() as conn:
  207. rs = conn.execute(db.text(sql_query), arg_dict)
  208. for i in rs:
  209. response_data.append({
  210. 'date': str(i.date),
  211. 'interactions': float(i.interactions.quantize(Decimal('0.01')))
  212. })
  213. return jsonify({
  214. 'data': response_data
  215. })
  216. api.add_resource(WorkflowDailyRunsStatistic, '/apps/<uuid:app_id>/workflow/statistics/daily-conversations')
  217. api.add_resource(WorkflowDailyTerminalsStatistic, '/apps/<uuid:app_id>/workflow/statistics/daily-terminals')
  218. api.add_resource(WorkflowDailyTokenCostStatistic, '/apps/<uuid:app_id>/workflow/statistics/token-costs')
  219. api.add_resource(WorkflowAverageAppInteractionStatistic, '/apps/<uuid:app_id>/workflow/statistics/average-app-interactions')