@brief Handle the chat request @param request the request @param send_response the send response @param send_streaming_response the send streaming response
| 705 | ///@param send_response the send response |
| 706 | ///@param send_streaming_response the send streaming response |
| 707 | void RestHandler::handle_chat(const json& request, |
| 708 | std::function<void(const json&)> send_response, |
| 709 | StreamResponseCallback send_streaming_response, |
| 710 | std::shared_ptr<CancellationToken> cancellation_token) { |
| 711 | try { |
| 712 | nlohmann::ordered_json messages = request["messages"]; |
| 713 | bool stream = request.value("stream", false); |
| 714 | std::string model = request.value("model", current_model_tag); |
| 715 | json options = request.value("options", json::object()); |
| 716 | int length_limit = options.value("num_predict", 4096); |
| 717 | |
| 718 | auto load_start_time = time_utils::now(); |
| 719 | if (!ensure_model_loaded(model)) { |
| 720 | json error_response = {{"error", "Failed to load " + model + " model!"}}; |
| 721 | send_response(error_response); |
| 722 | return; |
| 723 | } |
| 724 | auto load_end_time = time_utils::now(); |
| 725 | |
| 726 | configure_chat_engine_parameters(options, request); |
| 727 | |
| 728 | // messages = normalize_messages(messages); |
| 729 | |
| 730 | chat_meta_info_t meta_info; |
| 731 | lm_uniform_input_t uniformed_input; |
| 732 | meta_info.load_duration = (uint64_t)time_utils::duration_ns(load_start_time, load_end_time).first; |
| 733 | meta_info.max_prefill_len = this->prefill_chunk_len; |
| 734 | header_print("FLM", "Start generating..."); |
| 735 | if (stream) { |
| 736 | // Streaming response using streaming_ostream |
| 737 | auto total_start_time = time_utils::now(); |
| 738 | streaming_ostream ostream(model, send_streaming_response, true); // true for chat format |
| 739 | uniformed_input.messages = messages; |
| 740 | try { |
| 741 | bool success = auto_chat_engine->insert(meta_info, uniformed_input); |
| 742 | if (!success){ |
| 743 | json error_response = {{"error", "Max length reached"}}; |
| 744 | send_response(error_response); |
| 745 | this->auto_chat_engine->clear_context(); |
| 746 | return; |
| 747 | } |
| 748 | } catch (const std::exception& e) { |
| 749 | json error_response = {{"error", e.what()}}; |
| 750 | send_response(error_response); |
| 751 | this->auto_chat_engine->clear_context(); |
| 752 | return; |
| 753 | } |
| 754 | try { |
| 755 | bool success = auto_chat_engine->insert(meta_info, uniformed_input); |
| 756 | if (!success){ |
| 757 | json error_response = {{"error", "Max length reached"}}; |
| 758 | send_response(error_response); |
| 759 | this->auto_chat_engine->clear_context(); |
| 760 | return; |
| 761 | } |
| 762 | } catch (const std::exception& e) { |
| 763 | json error_response = {{"error", e.what()}}; |
| 764 | send_response(error_response); |
no test coverage detected