前言
rust 版 tokenizer 没有直接获取 chat template的方法,这里记录一下获取的方法
方案
手动复制保存
直接在模型库右边点Chat template
-> Copy
,保存下来

爬虫
用 reqwest
和 scraper
解析 html 取 div.SVELTE_HYDRATER.contents
的 data-props
属性转成 json 再过滤取到 chat template
rust
let repo = "Qwen/Qwen2.5-7B-Instruct";
let resp = Client::new()
.get(format!("https://huggingface.co/{repo}"))
.send()
.await?;
let document = Html::parse_document(&resp.text().await?);
let selector = Selector::parse("div.SVELTE_HYDRATER.contents").unwrap();
for elem in document.select(&selector) {
if let Some(attr) = elem.attr("data-props") {
let attr: Value = serde_json::from_str(attr)?;
println!("{:#?}", attr);
}
}
api
hugging face api没有提供chat template,但是可以通过api获取模型的配置信息再得到template
rust
let repo = "Qwen/Qwen2.5-7B-Instruct";
let repo = Api::new()?.model(repo.into());
let json: Value = repo.info_request().send().await?.json().await?;
let chat_template = json["config"]["tokenizer_config"]["chat_template"].as_str().unwrap();