#include "wrapper_chat_templates.h"
#include "wrapper_chat_templates_handle.h"
#include "wrapper_report_current_exception.h"
#include <common/chat.h>
#include <llama.h>
#include <exception>
#include <memory>
#include <new>
#include <string>
namespace {
auto default_template_source_of(const struct llama_model * model, const char * template_override) -> std::string {
if (*template_override != '\0') {
return template_override;
}
return llama_model_chat_template(model, nullptr);
}
auto templates_reporting_the_parse_error(const struct llama_model * model, const char * template_override)
-> common_chat_templates_ptr {
try {
return common_chat_templates_init(model, std::string(template_override));
} catch (const std::bad_alloc &) {
throw;
} catch (const std::exception &) {
const auto reparsed_template = std::make_unique<common_chat_template>(
default_template_source_of(model, template_override), std::string(), std::string());
throw;
}
}
}
extern "C" auto llama_rs_chat_templates_init(
const struct llama_model * model,
const char * template_override,
llama_rs_chat_templates_handle * out_templates,
char ** out_error) -> llama_rs_chat_templates_init_status {
*out_templates = nullptr;
*out_error = nullptr;
if (*template_override == '\0' && llama_model_chat_template(model, nullptr) == nullptr) {
return LLAMA_RS_CHAT_TEMPLATES_INIT_MODEL_HAS_NO_CHAT_TEMPLATE;
}
try {
auto templates = std::make_unique<llama_rs_chat_templates>();
templates->templates = templates_reporting_the_parse_error(model, template_override);
*out_templates = templates.release();
return LLAMA_RS_CHAT_TEMPLATES_INIT_OK;
} catch (...) {
return llama_rs_report_current_exception(
out_error,
LLAMA_RS_CHAT_TEMPLATES_INIT_LLAMA_CPP_OUT_OF_MEMORY,
LLAMA_RS_CHAT_TEMPLATES_INIT_LLAMA_CPP_THREW_CXX_EXCEPTION,
LLAMA_RS_CHAT_TEMPLATES_INIT_ERROR_STRING_ALLOCATION_FAILED);
}
}
extern "C" auto llama_rs_chat_templates_free(llama_rs_chat_templates_handle templates) -> void {
std::unique_ptr<llama_rs_chat_templates>(templates).reset();
}