| 65 | } |
| 66 | |
| 67 | bool Nanbeige::insert(chat_meta_info_t& meta_info, lm_uniform_input_t& input, std::function<bool()> is_cancelled) { |
| 68 | // preprocess |
| 69 | this->profiler_list[TKOEN_ENCODE_TIME].start(); |
| 70 | std::string templated_text; |
| 71 | if (input.messages.empty() && input.prompt.empty()) { |
| 72 | header_print("WARNING", "No messages or prompt provided"); |
| 73 | return false; |
| 74 | } |
| 75 | if (!input.messages.empty()) { // already a formated messages, usually from REST API |
| 76 | templated_text = this->apply_chat_template(input.messages, input.tools); |
| 77 | } |
| 78 | else if (!input.prompt.empty()) { // a pure text, usually from the cli |
| 79 | nlohmann::ordered_json messages; |
| 80 | |
| 81 | messages.push_back({ {"role", "user"}, {"content", input.prompt} }); |
| 82 | templated_text = this->apply_chat_template(messages); |
| 83 | } |
| 84 | |
| 85 | std::vector<int> tokens = this->tokenizer->encode(templated_text); |
| 86 | |
| 87 | this->profiler_list[TKOEN_ENCODE_TIME].stop(tokens.size()); |
| 88 | |
| 89 | // hardware |
| 90 | int restore_idx = -1; |
| 91 | nanbeige_npu *nanbeige_engine = dynamic_cast<nanbeige_npu*>(this->lm_engine.get()); |
| 92 | |
| 93 | if (meta_info.restore_allowed) { |
| 94 | restore_idx = nanbeige_engine->restore(); |
| 95 | this->total_tokens = restore_idx; |
| 96 | this->token_history = checkpoint_his; // restore the token history to be consistent with the restored KV cache, which is crucial for correct functioning of _shared_insert's prefix-matching logic |
| 97 | } |
| 98 | |
| 99 | bool success = this->_shared_insert(meta_info, tokens, is_cancelled, nullptr); |
| 100 | |
| 101 | checkpoint_his = token_history; |
| 102 | int checkpoint_idx = nanbeige_engine->checkpoint(); |
| 103 | |
| 104 | return success; |
| 105 | } |
| 106 | |
| 107 | |
| 108 | std::string Nanbeige::generate(chat_meta_info_t& meta_info, int length_limit, std::ostream& os, std::function<bool()> is_cancelled) { |
no test coverage detected