(session: SessionDep, current_user: CurrentUser, chat_record_id: int, action_type: str,
current_assistant: CurrentAssistant, in_chat: bool = True, stream: bool = True)
| 416 | |
| 417 | |
| 418 | async def analysis_or_predict(session: SessionDep, current_user: CurrentUser, chat_record_id: int, action_type: str, |
| 419 | current_assistant: CurrentAssistant, in_chat: bool = True, stream: bool = True): |
| 420 | try: |
| 421 | if action_type != 'analysis' and action_type != 'predict': |
| 422 | raise Exception(f"Type {action_type} Not Found") |
| 423 | record: ChatRecord | None = None |
| 424 | |
| 425 | stmt = select(ChatRecord.id, ChatRecord.question, ChatRecord.chat_id, ChatRecord.datasource, |
| 426 | ChatRecord.engine_type, |
| 427 | ChatRecord.ai_modal_id, ChatRecord.create_by, ChatRecord.chart, ChatRecord.data).where( |
| 428 | and_(ChatRecord.id == chat_record_id)) |
| 429 | result = session.execute(stmt) |
| 430 | for r in result: |
| 431 | record = ChatRecord(id=r.id, question=r.question, chat_id=r.chat_id, datasource=r.datasource, |
| 432 | engine_type=r.engine_type, ai_modal_id=r.ai_modal_id, create_by=r.create_by, |
| 433 | chart=r.chart, |
| 434 | data=r.data) |
| 435 | |
| 436 | if not record: |
| 437 | raise Exception(f"Chat record with id {chat_record_id} not found") |
| 438 | |
| 439 | if not record.chart: |
| 440 | raise Exception( |
| 441 | f"Chat record with id {chat_record_id} has not generated chart, do not support to analyze it") |
| 442 | |
| 443 | request_question = ChatQuestion(chat_id=record.chat_id, question=record.question) |
| 444 | |
| 445 | llm_service = await LLMService.create(session, current_user, request_question, current_assistant) |
| 446 | llm_service.run_analysis_or_predict_task_async(session, action_type, record, in_chat, stream) |
| 447 | except Exception as e: |
| 448 | traceback.print_exc() |
| 449 | if stream: |
| 450 | def _err(_e: Exception): |
| 451 | if in_chat: |
| 452 | yield 'data:' + orjson.dumps({'content': str(_e), 'type': 'error'}).decode() + '\n\n' |
| 453 | else: |
| 454 | yield f'❌ **ERROR:**\n' |
| 455 | yield f'> {str(_e)}\n' |
| 456 | |
| 457 | return StreamingResponse(_err(e), media_type="text/event-stream") |
| 458 | else: |
| 459 | return JSONResponse( |
| 460 | content={'message': str(e)}, |
| 461 | status_code=500, |
| 462 | ) |
| 463 | if stream: |
| 464 | return StreamingResponse(llm_service.await_result(), media_type="text/event-stream") |
| 465 | else: |
| 466 | res = llm_service.await_result() |
| 467 | raw_data = {} |
| 468 | for chunk in res: |
| 469 | if chunk: |
| 470 | raw_data = chunk |
| 471 | status_code = 200 |
| 472 | if not raw_data.get('success'): |
| 473 | status_code = 500 |
| 474 | |
| 475 | return JSONResponse( |
no test coverage detected