get_chat_template.py 2.8 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576
  1. #!/usr/bin/env python
  2. '''
  3. Fetches the Jinja chat template of a HuggingFace model.
  4. If a model has multiple chat templates, you can specify the variant name.
  5. Syntax:
  6. ./scripts/get_chat_template.py model_id [variant]
  7. Examples:
  8. ./scripts/get_chat_template.py CohereForAI/c4ai-command-r-plus tool_use
  9. ./scripts/get_chat_template.py microsoft/Phi-3.5-mini-instruct
  10. '''
  11. import json
  12. import re
  13. import sys
  14. def get_chat_template(model_id, variant=None):
  15. try:
  16. # Use huggingface_hub library if available.
  17. # Allows access to gated models if the user has access and ran `huggingface-cli login`.
  18. from huggingface_hub import hf_hub_download
  19. with open(hf_hub_download(repo_id=model_id, filename="tokenizer_config.json"), encoding="utf-8") as f:
  20. config_str = f.read()
  21. except ImportError:
  22. import requests
  23. assert re.match(r"^[\w.-]+/[\w.-]+$", model_id), f"Invalid model ID: {model_id}"
  24. response = requests.get(f"https://huggingface.co/{model_id}/resolve/main/tokenizer_config.json")
  25. if response.status_code == 401:
  26. raise Exception('Access to this model is gated, please request access, authenticate with `huggingface-cli login` and make sure to run `pip install huggingface_hub`')
  27. response.raise_for_status()
  28. config_str = response.text
  29. try:
  30. config = json.loads(config_str)
  31. except json.JSONDecodeError:
  32. # Fix https://huggingface.co/NousResearch/Meta-Llama-3-8B-Instruct/blob/main/tokenizer_config.json
  33. # (Remove extra '}' near the end of the file)
  34. config = json.loads(re.sub(r'\}([\n\s]*\}[\n\s]*\],[\n\s]*"clean_up_tokenization_spaces")', r'\1', config_str))
  35. chat_template = config['chat_template']
  36. if isinstance(chat_template, str):
  37. return chat_template
  38. else:
  39. variants = {
  40. ct['name']: ct['template']
  41. for ct in chat_template
  42. }
  43. def format_variants():
  44. return ', '.join(f'"{v}"' for v in variants.keys())
  45. if variant is None:
  46. if 'default' not in variants:
  47. raise Exception(f'Please specify a chat template variant (one of {format_variants()})')
  48. variant = 'default'
  49. sys.stderr.write(f'Note: picked "default" chat template variant (out of {format_variants()})\n')
  50. elif variant not in variants:
  51. raise Exception(f"Variant {variant} not found in chat template (found {format_variants()})")
  52. return variants[variant]
  53. def main(args):
  54. if len(args) < 1:
  55. raise ValueError("Please provide a model ID and an optional variant name")
  56. model_id = args[0]
  57. variant = None if len(args) < 2 else args[1]
  58. template = get_chat_template(model_id, variant)
  59. sys.stdout.write(template)
  60. if __name__ == '__main__':
  61. main(sys.argv[1:])