自定义聊天模板

自定义聊天模板#

通过设置日志级别 INFO,可以观察到应用的聊天模板的效果。

LMDeploy 支持两种添加聊天模板的方法:

  • 一种方法是直接配置一个JSON文件来利用现有的对话模板,如下所示。

    {
        "model_name": "your awesome chat template name",
        "system": "<|im_start|>system\n",
        "meta_instruction": "You are a robot developed by LMDeploy.",
        "eosys": "<|im_end|>\n",
        "user": "<|im_start|>user\n",
        "eoh": "<|im_end|>\n",
        "assistant": "<|im_start|>assistant\n",
        "eoa": "<|im_end|>",
        "separator": "\n",
        "capability": "chat",
        "stop_words": ["<|im_end|>"]
    }
    

    model_name 是一个必填字段,可以是 LMDeploy 内置聊天模板的名称(可以通过 lmdeploy list 查看),也可以是一个新名称。其他字段是可选的。

    1. model_name是内置聊天模板的名称时,JSON文件中的非空字段将覆盖原始聊天模板的相应属性。

    2. 然而,当model_name是一个新名称时,它将直接注册BaseChatTemplate作为一个新的聊天模板。具体定义可以参考BaseChatTemplate

    新的聊天模板将会是这样的:

    {system}{meta_instruction}{eosys}{user}{user_content}{eoh}{assistant}{assistant_content}{eoa}{separator}{user}...
    

    使用CLI工具时,您可以传入一个自定义的聊天模板,例如使用--chat-template

    lmdeploy serve api_server internlm/internlm2_5-7b-chat --chat-template ${JSON_FILE}
    

    你也可以通过接口函数传递它,例如。

    from lmdeploy import ChatTemplateConfig, serve
    serve('internlm/internlm2_5-7b-chat',
          chat_template_config=ChatTemplateConfig.from_json('${JSON_FILE}'))
    
  • 另一种方法是自定义一个Python聊天模板类,如现有的LMDeploy聊天模板。成功注册后可以直接使用。其优点是高度定制化和强大的可控性。以下是注册LMDeploy聊天模板的示例。

    from lmdeploy.model import MODELS, BaseChatTemplate
    
    
    @MODELS.register_module(name='customized_model')
    class CustomizedModel(BaseChatTemplate):
        """A customized chat template."""
    
        def __init__(self,
                     system='<|im_start|>system\n',
                     meta_instruction='You are a robot developed by LMDeploy.',
                     user='<|im_start|>user\n',
                     assistant='<|im_start|>assistant\n',
                     eosys='<|im_end|>\n',
                     eoh='<|im_end|>\n',
                     eoa='<|im_end|>',
                     separator='\n',
                     stop_words=['<|im_end|>', '<|action_end|>']):
            super().__init__(system=system,
                             meta_instruction=meta_instruction,
                             eosys=eosys,
                             user=user,
                             eoh=eoh,
                             assistant=assistant,
                             eoa=eoa,
                             separator=separator,
                             stop_words=stop_words)
    
    
    from lmdeploy import ChatTemplateConfig, pipeline
    
    messages = [{'role': 'user', 'content': 'who are you?'}]
    pipe = pipeline('internlm/internlm2_5-7b-chat',
                    chat_template_config=ChatTemplateConfig('customized_model'))
    for response in pipe.stream_infer(messages):
        print(response.text, end='')
    

    在这个例子中,我们注册了一个LMDeploy聊天模板,该模板设置由LMDeploy创建的模型,因此当用户询问模型是谁时,模型会回答它是由LMDeploy创建的。