| 47 | |
| 48 | |
| 49 | class WorkFlowPostHandler: |
| 50 | def __init__(self, chat_info): |
| 51 | self.chat_info = chat_info |
| 52 | |
| 53 | def handler(self, workflow): |
| 54 | workflow_body = workflow.get_body() |
| 55 | question = workflow_body.get('question') |
| 56 | chat_record_id = workflow_body.get('chat_record_id') |
| 57 | chat_id = workflow_body.get('chat_id') |
| 58 | details = workflow.get_runtime_details() |
| 59 | message_tokens = sum([row.get('message_tokens') for row in details.values() if |
| 60 | 'message_tokens' in row and row.get('message_tokens') is not None]) |
| 61 | answer_tokens = sum([row.get('answer_tokens') for row in details.values() if |
| 62 | 'answer_tokens' in row and row.get('answer_tokens') is not None]) |
| 63 | answer_text_list = workflow.get_answer_text_list() |
| 64 | answer_text = '\n\n'.join( |
| 65 | '\n\n'.join([a.get('content') for a in answer]) for answer in |
| 66 | answer_text_list) |
| 67 | if workflow.chat_record is not None: |
| 68 | chat_record = workflow.chat_record |
| 69 | chat_record.problem_text = question |
| 70 | chat_record.answer_text = answer_text |
| 71 | chat_record.details = details |
| 72 | chat_record.message_tokens = message_tokens |
| 73 | chat_record.answer_tokens = answer_tokens |
| 74 | chat_record.answer_text_list = answer_text_list |
| 75 | chat_record.run_time = time.time() - workflow.context['start_time'] |
| 76 | else: |
| 77 | chat_record = ChatRecord(id=chat_record_id, |
| 78 | chat_id=chat_id, |
| 79 | problem_text=question, |
| 80 | answer_text=answer_text, |
| 81 | details=details, |
| 82 | message_tokens=message_tokens, |
| 83 | answer_tokens=answer_tokens, |
| 84 | answer_text_list=answer_text_list, |
| 85 | run_time=time.time() - workflow.context.get('start_time') if workflow.context.get( |
| 86 | 'start_time') is not None else 0, |
| 87 | index=0, |
| 88 | ip_address=self.chat_info.ip_address, |
| 89 | source=self.chat_info.source) |
| 90 | |
| 91 | self.chat_info.append_chat_record(chat_record) |
| 92 | self.chat_info.set_cache() |
| 93 | |
| 94 | if not self.chat_info.debug and [ChatUserType.ANONYMOUS_USER.value, ChatUserType.CHAT_USER.value].__contains__( |
| 95 | workflow_body.get('chat_user_type')): |
| 96 | application_public_access_client = (QuerySet(ApplicationChatUserStats) |
| 97 | .filter(chat_user_id=workflow_body.get('chat_user_id'), |
| 98 | chat_user_type=workflow_body.get('chat_user_type'), |
| 99 | application_id=self.chat_info.application_id).first()) |
| 100 | if application_public_access_client is not None: |
| 101 | application_public_access_client.access_num = application_public_access_client.access_num + 1 |
| 102 | application_public_access_client.intraday_access_num = application_public_access_client.intraday_access_num + 1 |
| 103 | application_public_access_client.save() |
| 104 | self.chat_info = None |
| 105 | |
| 106 | extract_long_term_memory.apply_async( |