Skip to content
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
32 changes: 32 additions & 0 deletions examples/rag_template_cohere.jinja
Original file line number Diff line number Diff line change
@@ -0,0 +1,32 @@
{% if messages[0]['role'] == 'system' %}
{% set loop_messages = messages[1:] %}
{% set system_message = messages[0]['content'] %}
{% else %}
{% set loop_messages = messages %}
{% set system_message = '## Task and Context\nYou help people answer their questions and other requests interactively. You will be asked a very wide array of requests on all kinds of topics. You will be equipped with a wide range of search engines or similar tools to help you, which you use to research your answer. You should focus on serving the user\'s needs as best you can, which will be wide-ranging.\n\n## Style Guide\nUnless the user asks for a different style of answer, you should answer in full sentences, using proper grammar and spelling.' %}
{% endif %}
{{ '<|START_OF_TURN_TOKEN|><|SYSTEM_TOKEN|>' }}{{ '# Safety Preamble' }}
{{ 'The instructions in this section override those in the task description and style guide sections. Don\'t answer questions that are harmful or immoral.' }}

{{ '# System Preamble' }}
{{ '## Basic Rules' }}
{{ 'You are a powerful conversational AI trained by Cohere to help people. You are augmented by a number of tools, and your job is to use and consume the output of these tools to best help the user. You will see a conversation history between yourself and a user, ending with an utterance from the user. You will then see a specific instruction instructing you what kind of response to generate. When you answer the user\'s requests, you cite your sources in your answers, according to those instructions.' }}

{{ '# User Preamble' }}
{{ system_message }}{{ '<|END_OF_TURN_TOKEN|>'}}{% for message in loop_messages %}{% set content = message['content'] %}{% if message['role'] == 'user' %}{{ '<|START_OF_TURN_TOKEN|><|USER_TOKEN|>' + content.strip() + '<|END_OF_TURN_TOKEN|>' }}{% elif message['role'] == 'system' %}{{ '<|START_OF_TURN_TOKEN|><|SYSTEM_TOKEN|>' + content.strip() + '<|END_OF_TURN_TOKEN|>' }}{% elif message['role'] == 'assistant' %}{{ '<|START_OF_TURN_TOKEN|><|CHATBOT_TOKEN|>' + content.strip() + '<|END_OF_TURN_TOKEN|>' }}{% endif %}
{% endfor %}
{{ '<|START_OF_TURN_TOKEN|><|SYSTEM_TOKEN|>'}}{{ '<results>' }}{% for document in documents %}

{{ 'Document: ' }}{{ loop.index0 }}
{% for key, value in document.items() %}
{{ key }}: {{value}}
{% endfor %}
{% endfor %}
{{ '</results>'}}{{ '<|END_OF_TURN_TOKEN|><|START_OF_TURN_TOKEN|><|SYSTEM_TOKEN|>' }}{{ 'Carefully perform the following instructions, in order, starting each with a new line.' }}
{{ 'Firstly, Decide which of the retrieved documents are relevant to the user\'s last input by writing \'Relevant Documents:\' followed by comma-separated list of document numbers. If none are relevant, you should instead write \'None\'.' }}
{{ 'Secondly, Decide which of the retrieved documents contain facts that should be cited in a good answer to the user\'s last input by writing \'Cited Documents:\' followed a comma-separated list of document numbers. If you dont want to cite any of them, you should instead write \'None\'.' }}
{% if citation_mode=='accurate' %}
{{ 'Thirdly, Write \'Answer:\' followed by a response to the user\'s last input in high quality natural english. Use the retrieved documents to help you. Do not insert any citations or grounding markup.' }}
{% endif %}
{{ 'Finally, Write \'Grounded answer:\' followed by a response to the user\'s last input in high quality natural english. Use the symbols <co: doc> and </co: doc> to indicate when a fact comes from a document in the search result, e.g <co: 0>my fact</co: 0> for a fact from document 0.' }}{{ '<|END_OF_TURN_TOKEN|>' }}{% if add_generation_prompt %}
{{ '<|START_OF_TURN_TOKEN|><|CHATBOT_TOKEN|>' }}{% endif %}
40 changes: 40 additions & 0 deletions examples/tool_template_cohere.jinja
Original file line number Diff line number Diff line change
@@ -0,0 +1,40 @@
{% if messages[0]['role'] == 'system' %}
{% set loop_messages = messages[1:] %}
{% set system_message = messages[0]['content'] %}
{% else %}
{% set loop_messages = messages %}
{% set system_message = '## Task and Context
You help people answer their questions and other requests interactively. You will be asked a very wide array of requests on all kinds of topics. You will be equipped with a wide range of search engines or similar tools to help you, which you use to research your answer. You should focus on serving the user\'s needs as best you can, which will be wide-ranging.\n\n## Style Guide
Unless the user asks for a different style of answer, you should answer in full sentences, using proper grammar and spelling.' %}
{% endif %}
{{ '<|START_OF_TURN_TOKEN|><|SYSTEM_TOKEN|>' }}{{ '# Safety Preamble' }}
{{ 'The instructions in this section override those in the task description and style guide sections. Don\'t answer questions that are harmful or immoral.' }}
{{ '\n# System Preamble' }}
{{ '## Basic Rules' }}
{{ 'You are a powerful conversational AI trained by Cohere to help people. You are augmented by a number of tools, and your job is to use and consume the output of these tools to best help the user. You will see a conversation history between yourself and a user, ending with an utterance from the user. You will then see a specific instruction instructing you what kind of response to generate. When you answer the user\'s requests, you cite your sources in your answers, according to those instructions.' }}
{{ '\n# User Preamble' }}
{{ system_message }}
{{'\n## Available Tools\nHere is a list of tools that you have available to you:\n'}}
{% for tool in tools %}
{% if loop.index0 != 0 %}
{{ '\n'}}
{% endif %}
{{'```python\ndef ' + tool.name + '('}}{% for param_name, param_fields in tool.parameter_definitions.items() %}{% if loop.index0 != 0 %}{{ ', '}}
{% endif %}{{param_name}}: {% if not param_fields.required %}{{'Optional[' + param_fields.type + '] = None'}}
{% else %}{{ param_fields.type }}{% endif %}
{% endfor %}
{{ ') -> List[Dict]:\n """'}}{{ tool.description }}
{% if tool.parameter_definitions|length != 0 %}
{{ '\n Args:\n '}}{% for param_name, param_fields in tool.parameter_definitions.items() %}
{% if loop.index0 != 0 %}
{{ ' ' }}
{% endif %}{{ param_name + ' ('}}{% if not param_fields.required %}{{'Optional[' + param_fields.type + ']'}}
{% else %}{{ param_fields.type }}{% endif %}{{ '): ' + param_fields.description }}
{% endfor %}
{% endif %}
{{ ' """\n pass\n```' }}{% endfor %}{{ '<|END_OF_TURN_TOKEN|>'}}{% for message in loop_messages %}{% set content = message['content'] %}
{% if message['role'] == 'user' %}{{ '<|START_OF_TURN_TOKEN|><|USER_TOKEN|>' + content.strip() + '<|END_OF_TURN_TOKEN|>' }}{% elif message['role'] == 'system' %}{{ '<|START_OF_TURN_TOKEN|><|SYSTEM_TOKEN|>' + content.strip() + '<|END_OF_TURN_TOKEN|>' }}{% elif message['role'] == 'assistant' %}{{ '<|START_OF_TURN_TOKEN|><|CHATBOT_TOKEN|>' + content.strip() + '<|END_OF_TURN_TOKEN|>' }}
{% endif %}
{% endfor %}
{{'<|START_OF_TURN_TOKEN|><|SYSTEM_TOKEN|>Write \'Action:\' followed by a json-formatted list of actions that you want to perform in order to produce a good response to the user\'s last input. You can use any of the supplied tools any number of times, but you should aim to execute the minimum number of necessary actions for the input. You should use the `directly-answer` tool if calling the other tools is unnecessary. The list of actions you want to call should be formatted as a list of json objects, for example:\n```json\n[\n {\n \"tool_name\": title of the tool in the specification,\n \"parameters\": a dict of parameters to input into the tool as they are defined in the specs, or {} if it takes no parameters\n }\n]```<|END_OF_TURN_TOKEN|>'}}{% if add_generation_prompt %}
{{ '<|START_OF_TURN_TOKEN|><|CHATBOT_TOKEN|>' }}{% endif %}
13 changes: 9 additions & 4 deletions vllm/entrypoints/openai/api_server.py
Original file line number Diff line number Diff line change
Expand Up @@ -158,10 +158,15 @@ async def authentication(request: Request, call_next):
engine_args = AsyncEngineArgs.from_cli_args(args)
engine = AsyncLLMEngine.from_engine_args(
engine_args, usage_context=UsageContext.OPENAI_API_SERVER)
openai_serving_chat = OpenAIServingChat(engine, served_model_names,
args.response_role,
args.lora_modules,
args.chat_template)
openai_serving_chat = OpenAIServingChat(
engine,
served_model_names,
args.response_role,
args.lora_modules,
args.chat_template,
args.tool_template,
args.rag_template,
)
openai_serving_completion = OpenAIServingCompletion(
engine, served_model_names, args.lora_modules)

Expand Down
12 changes: 12 additions & 0 deletions vllm/entrypoints/openai/cli_args.py
Original file line number Diff line number Diff line change
Expand Up @@ -77,6 +77,18 @@ def make_arg_parser():
help="The file path to the chat template, "
"or the template in single-line form "
"for the specified model")
parser.add_argument("--tool-template",
type=str,
default=None,
help="The file path to the tool template, "
"or the template in single-line form "
"for the specified model")
parser.add_argument("--rag-template",
type=str,
default=None,
help="The file path to the rag template, "
"or the template in single-line form "
"for the specified model")
parser.add_argument("--response-role",
type=str,
default="assistant",
Expand Down
2 changes: 2 additions & 0 deletions vllm/entrypoints/openai/protocol.py
Original file line number Diff line number Diff line change
Expand Up @@ -64,6 +64,8 @@ class ChatCompletionRequest(BaseModel):
# Ordered by official OpenAI API documentation
# https://platform.openai.com/docs/api-reference/chat/create
messages: List[Dict[str, str]]
tools: Optional[List[Dict[str, Union[str, Dict]]]] = None
documents: Optional[List[Dict[str, str]]] = None
model: str
frequency_penalty: Optional[float] = 0.0
logit_bias: Optional[Dict[str, float]] = None
Expand Down
82 changes: 72 additions & 10 deletions vllm/entrypoints/openai/serving_chat.py
Original file line number Diff line number Diff line change
Expand Up @@ -22,17 +22,26 @@

class OpenAIServingChat(OpenAIServing):

def __init__(self,
engine: AsyncLLMEngine,
served_model_names: List[str],
response_role: str,
lora_modules: Optional[List[LoRA]] = None,
chat_template=None):
def __init__(
self,
engine: AsyncLLMEngine,
served_model_names: List[str],
response_role: str,
lora_modules: Optional[List[LoRA]] = None,
chat_template=None,
tool_template=None,
rag_template=None,
):
super().__init__(engine=engine,
served_model_names=served_model_names,
lora_modules=lora_modules)
self.response_role = response_role
self._load_chat_template(chat_template)
if tool_template is not None:
self._load_tool_template(tool_template)

if rag_template is not None:
self._load_rag_template(rag_template)

async def create_chat_completion(
self, request: ChatCompletionRequest, raw_request: Request
Expand All @@ -52,10 +61,25 @@ async def create_chat_completion(
return error_check_ret

try:
prompt = self.tokenizer.apply_chat_template(
conversation=request.messages,
tokenize=False,
add_generation_prompt=request.add_generation_prompt)
if request.tools is not None:
prompt = self.tokenizer.apply_chat_template(
conversation=request.messages,
chat_template="tool_use",
tools=request.tools,
tokenize=False,
add_generation_prompt=request.add_generation_prompt)
elif request.documents is not None:
prompt = self.tokenizer.apply_chat_template(
conversation=request.messages,
chat_template="rag",
documents=request.documents,
tokenize=False,
add_generation_prompt=request.add_generation_prompt)
else:
prompt = self.tokenizer.apply_chat_template(
conversation=request.messages,
tokenize=False,
add_generation_prompt=request.add_generation_prompt)
except Exception as e:
logger.error(
f"Error in applying chat template from request: {str(e)}")
Expand Down Expand Up @@ -346,3 +370,41 @@ def _load_chat_template(self, chat_template):
else:
logger.warning(
"No chat template provided. Chat API will not work.")

def _load_tool_template(self, tool_template):
try:
with open(tool_template, "r") as f:
tool_template = f.read()
except OSError:
# If opening a file fails, set chat template to be args to
# ensure we decode so our escape are interpreted correctly
tool_template = codecs.decode(tool_template, "unicode_escape")

if isinstance(self.tokenizer.chat_template, dict):
self.tokenizer.chat_template['tool_use'] = tool_template
else:
self.tokenizer.chat_template = {
"default": self.tokenizer.chat_template,
'tool_use': tool_template
}

logger.info(f"Using supplied tool template:\n{tool_template}")

def _load_rag_template(self, rag_template):
try:
with open(rag_template, "r") as f:
rag_template = f.read()
except OSError:
# If opening a file fails, set chat template to be args to
# ensure we decode so our escape are interpreted correctly
rag_template = codecs.decode(rag_template, "unicode_escape")

if isinstance(self.tokenizer.chat_template, dict):
self.tokenizer.chat_template['rag'] = rag_template
else:
self.tokenizer.chat_template = {
"default": self.tokenizer.chat_template,
'rag': rag_template
}

logger.info(f"Using supplied rag template:\n{rag_template}")