helper function to evaluate a prompt and generate a response
| 986 | |
| 987 | // helper function to evaluate a prompt and generate a response |
| 988 | static int generate(LlamaData & llama_data, const std::string & prompt, std::string & response) { |
| 989 | const llama_vocab * vocab = llama_model_get_vocab(llama_data.model.get()); |
| 990 | |
| 991 | std::vector<llama_token> tokens; |
| 992 | if (tokenize_prompt(vocab, prompt, tokens, llama_data) < 0) { |
| 993 | return 1; |
| 994 | } |
| 995 | |
| 996 | // prepare a batch for the prompt |
| 997 | llama_batch batch = llama_batch_get_one(tokens.data(), tokens.size()); |
| 998 | llama_token new_token_id; |
| 999 | while (true) { |
| 1000 | check_context_size(llama_data.context, batch); |
| 1001 | if (llama_decode(llama_data.context.get(), batch)) { |
| 1002 | printe("failed to decode\n"); |
| 1003 | return 1; |
| 1004 | } |
| 1005 | |
| 1006 | // sample the next token, check is it an end of generation? |
| 1007 | new_token_id = llama_sampler_sample(llama_data.sampler.get(), llama_data.context.get(), -1); |
| 1008 | if (llama_vocab_is_eog(vocab, new_token_id)) { |
| 1009 | break; |
| 1010 | } |
| 1011 | |
| 1012 | std::string piece; |
| 1013 | if (convert_token_to_string(vocab, new_token_id, piece)) { |
| 1014 | return 1; |
| 1015 | } |
| 1016 | |
| 1017 | print_word_and_concatenate_to_response(piece, response); |
| 1018 | |
| 1019 | // prepare the next batch with the sampled token |
| 1020 | batch = llama_batch_get_one(&new_token_id, 1); |
| 1021 | } |
| 1022 | |
| 1023 | printf(LOG_COL_DEFAULT); |
| 1024 | return 0; |
| 1025 | } |
| 1026 | |
| 1027 | static int read_user_input(std::string & user_input) { |
| 1028 | static const char * prompt_prefix_env = std::getenv("LLAMA_PROMPT_PREFIX"); |
no test coverage detected