你当前正在访问 Microsoft Azure Global Edition 技术文档网站。 如果需要访问由世纪互联运营的 Microsoft Azure 中国技术文档网站,请访问 https://docs.azure.cn

聊天标记语言 ChatML(预览版)

重要

本文所述的将 GPT-3.5-Turbo 模型与补全终结点配合使用的功能仍为预览版,仅可与 gpt-35-turbo 版本 (0301) 配合使用,后者最早在 2024 年 8 月 1 日停用。 强烈建议使用 GA 聊天补全 API/终结点。 建议使用聊天补全 API 与 GPT-3.5-Turbo 模型进行交互。 也只能通过聊天补全 API 来使用 GPT-4 模型。

以下代码片段演示了通过 ChatML 使用 GPT-3.5-Turbo 模型的最基本的方法。 如果这是你第一次以编程方式使用这些模型,建议先从 GPT-35-Turbo 和 GPT-4 快速入门开始。

注意

在 Azure OpenAI 文档中,我们交替引用了 GPT-3.5-Turbo 和 GPT-35-Turbo。 OpenAI 上的模型的官方名称是 gpt-3.5-turbo,但对于 Azure OpenAI,由于 Azure 特定的字符约束,基础模型名称为 gpt-35-turbo

import os
import openai
openai.api_type = "azure"
openai.api_base = "https://{your-resource-name}.openai.azure.com/"
openai.api_version = "2024-02-01"
openai.api_key = os.getenv("OPENAI_API_KEY")

response = openai.Completion.create(
  engine="gpt-35-turbo", # The deployment name you chose when you deployed the GPT-35-Turbo model
  prompt="<|im_start|>system\nAssistant is a large language model trained by OpenAI.\n<|im_end|>\n<|im_start|>user\nWho were the founders of Microsoft?\n<|im_end|>\n<|im_start|>assistant\n",
  temperature=0,
  max_tokens=500,
  top_p=0.5,
  stop=["<|im_end|>"])

print(response['choices'][0]['text'])

注意

以下参数不适用于 gpt-35-turbo 模型:logprobsbest_ofecho。 如果你设置了这些参数中的任何一个,则会收到错误。

<|im_end|> 标记指示消息的结束。 使用 ChatML 时,建议将 <|im_end|> 标记作为停止序列包含在内,以确保模型在到达消息末尾时停止生成文本。

考虑将 max_tokens 设置为略高于正常值,例如 300 或 500。 这可确保模型在到达消息末尾之前不会停止生成文本。

模型版本控制

注意

gpt-35-turbo 等效于 OpenAI 中的 gpt-3.5-turbo 模型。

与以前的 GPT-3 和 GPT-3.5 模型不同,gpt-35-turbo 模型以及 gpt-4gpt-4-32k 模型将继续更新。 创建这些模型的部署时,还需要指定模型版本。

可在我们的模型页上找到这些模型的模型停用日期。

使用聊天标记语言 (ChatML)

注意

OpenAI 会持续改进 GPT-35-Turbo,用于模型的聊天标记语言将来会继续演变。 我们将在此文档中更新最新信息。

OpenAI 使用特殊标记对 GPT-35-Turbo 进行训练,以标明提示的不同部分。 提示从用于启动模型的系统消息开始,然后是用户和助手之间的一系列消息。

基本 ChatML 提示的格式如下所示:

<|im_start|>system 
Provide some context and/or instructions to the model.
<|im_end|> 
<|im_start|>user 
The user’s message goes here
<|im_end|> 
<|im_start|>assistant 

系统消息

系统消息包含在 <|im_start|>system<|im_end|> 标记之间的提示的开头。 此消息提供模型的初始说明。 可以在系统消息中提供各种信息,包括:

  • 助手的简要说明
  • 助手的个性特征
  • 你希望助手遵循的指令或规则
  • 模型所需的数据或信息,例如 FAQ 中的相关问题

可以为你的用例自定义系统消息,也可以仅包含基本系统消息。 系统消息是可选的,但建议至少包含一个基本消息,以获得最佳结果。

消息

在系统消息之后,可以在用户助手之间加入一系列消息。 每条消息都应以 <|im_start|> 标记开头,后跟角色(userassistant),以 <|im_end|> 标记结尾。

<|im_start|>user
What is thermodynamics?
<|im_end|>

若要触发模型的回复,提示应以 <|im_start|>assistant 标记结尾,指示轮到助手回复了。 还可以在提示中加入用户和助手之间的消息,作为进行少样本学习的方式。

提示示例

以下部分展示了可用于 GPT-35-Turbo 和 GPT-4 模型的不同提示样式的示例。 这些示例只是为了抛砖引玉,你可以尝试使用不同的提示来为自己的用例自定义行为。

基本示例

如果你希望 GPT-35-Turbo 和 GPT-4 模型的行为类似于 chat.openai.com,可以使用基本系统消息,例如“助手是 OpenAI 训练的大型语言模型”。

<|im_start|>system
Assistant is a large language model trained by OpenAI.
<|im_end|>
<|im_start|>user
Who were the founders of Microsoft?
<|im_end|>
<|im_start|>assistant

说明的示例

对于某些场景,你可能希望向模型提供其他说明,以定义模型能够执行的操作的边界。

<|im_start|>system
Assistant is an intelligent chatbot designed to help users answer their tax related questions. 

Instructions:
- Only answer questions related to taxes. 
- If you're unsure of an answer, you can say "I don't know" or "I'm not sure" and recommend users go to the IRS website for more information.
<|im_end|>
<|im_start|>user
When are my taxes due?
<|im_end|>
<|im_start|>assistant

使用数据进行验证

你还可以在系统消息中加入相关数据或信息,为模型提供额外的对话上下文。 如果只需要包含少量信息,则可以将其硬编码到系统消息中。 如果你有模型应注意的大量数据,则可以使用嵌入Azure AI 搜索等产品在查询时检索最相关的信息。

<|im_start|>system
Assistant is an intelligent chatbot designed to help users answer technical questions about Azure OpenAI Serivce. Only answer questions using the context below and if you're not sure of an answer, you can say "I don't know".

Context:
- Azure OpenAI Service provides REST API access to OpenAI's powerful language models including the GPT-3, Codex and Embeddings model series.
- Azure OpenAI Service gives customers advanced language AI with OpenAI GPT-3, Codex, and DALL-E models with the security and enterprise promise of Azure. Azure OpenAI co-develops the APIs with OpenAI, ensuring compatibility and a smooth transition from one to the other.
- At Microsoft, we're committed to the advancement of AI driven by principles that put people first. Microsoft has made significant investments to help guard against abuse and unintended harm, which includes requiring applicants to show well-defined use cases, incorporating Microsoft’s principles for responsible AI use
<|im_end|>
<|im_start|>user
What is Azure OpenAI Service?
<|im_end|>
<|im_start|>assistant

使用 ChatML 进行少样本学习

还可以为模型提供少样本学习的示例。 由于新的提示格式,少样本学习的方法略有变化。 现在可以在提示中加入用户和助理之间的一系列消息,作为少样本学习示例。 这些例子可以用来为常见问题设定回答,以启动模型或教它特定的行为。

这只是通过 GPT-35-Turbo 使用少样本学习的其中一个示例。 可以尝试不同的方法,看看哪种方法最适合你的用例。

<|im_start|>system
Assistant is an intelligent chatbot designed to help users answer their tax related questions. 
<|im_end|>
<|im_start|>user
When do I need to file my taxes by?
<|im_end|>
<|im_start|>assistant
In 2023, you will need to file your taxes by April 18th. The date falls after the usual April 15th deadline because April 15th falls on a Saturday in 2023. For more details, see https://www.irs.gov/filing/individuals/when-to-file
<|im_end|>
<|im_start|>user
How can I check the status of my tax refund?
<|im_end|>
<|im_start|>assistant
You can check the status of your tax refund by visiting https://www.irs.gov/refunds
<|im_end|>

在非聊天场景中使用聊天标记语言

ChatML 旨在使多轮次对话更易于管理,但它也适用于非聊天场景。

例如,对于实体提取场景,可以使用以下提示:

<|im_start|>system
You are an assistant designed to extract entities from text. Users will paste in a string of text and you will respond with entities you've extracted from the text as a JSON object. Here's an example of your output format:
{
   "name": "",
   "company": "",
   "phone_number": ""
}
<|im_end|>
<|im_start|>user
Hello. My name is Robert Smith. I’m calling from Contoso Insurance, Delaware. My colleague mentioned that you are interested in learning about our comprehensive benefits policy. Could you give me a call back at (555) 346-9322 when you get a chance so we can go over the benefits?
<|im_end|>
<|im_start|>assistant

防止不安全的用户输入

请务必将缓解措施添加到你的应用程序中,以确保安全使用聊天标记语言。

建议阻止最终用户在其输入中加入特殊标记,例如 <|im_start|><|im_end|>。 我们还建议加入其他验证,以确保发送到模型的提示格式正确,并遵循本文档中所述的聊天标记语言格式。

还可以在系统消息中提供说明,指导模型如何响应某些类型的用户输入。 例如,可以指示模型仅回复有关特定主题的消息。 还可以通过少样本学习示例来强化此行为。

管理对话

gpt-35-turbo 的标记限制为 4096 个标记。 此限制包括来自提示和补全的标记数。 与 max_tokens 参数的值组合在一起的提示中的标记数必须保持在 4096 以下,否则将收到错误。

你有责任确保提示和补全操作在标记限制范围内。 这意味着,对于较长的对话,需要跟踪标记数,并仅向模型发送在标记限制以内的提示。

以下简易代码示例演示了如何跟踪会话中的单独消息。

import os
import openai
openai.api_type = "azure"
openai.api_base = "https://{your-resource-name}.openai.azure.com/" #This corresponds to your Azure OpenAI resource's endpoint value
openai.api_version = "2024-02-01" 
openai.api_key = os.getenv("OPENAI_API_KEY")

# defining a function to create the prompt from the system message and the conversation messages
def create_prompt(system_message, messages):
    prompt = system_message
    for message in messages:
        prompt += f"\n<|im_start|>{message['sender']}\n{message['text']}\n<|im_end|>"
    prompt += "\n<|im_start|>assistant\n"
    return prompt

# defining the user input and the system message
user_input = "<your user input>" 
system_message = f"<|im_start|>system\n{'<your system message>'}\n<|im_end|>"

# creating a list of messages to track the conversation
messages = [{"sender": "user", "text": user_input}]

response = openai.Completion.create(
    engine="gpt-35-turbo", # The deployment name you chose when you deployed the GPT-35-Turbo model.
    prompt=create_prompt(system_message, messages),
    temperature=0.5,
    max_tokens=250,
    top_p=0.9,
    frequency_penalty=0,
    presence_penalty=0,
    stop=['<|im_end|>']
)

messages.append({"sender": "assistant", "text": response['choices'][0]['text']})
print(response['choices'][0]['text'])

控制在标记限制之下

控制在标记限制之下的最简单方法是在达到标记限制时删除对话中最早的消息。

可以选择始终包含尽可能多的标记,同时保持在限制范围内,也可以始终包含一定数量的先前消息(假设这些消息能保持在限制范围内)。 请务必记住,与较短的提示相比,较长的提示需要更长的时间生成回复并产生更高的成本。

可以使用 tiktoken Python 库估计字符串中的标记数,如下所示。

import tiktoken 

cl100k_base = tiktoken.get_encoding("cl100k_base") 

enc = tiktoken.Encoding( 
    name="gpt-35-turbo",  
    pat_str=cl100k_base._pat_str, 
    mergeable_ranks=cl100k_base._mergeable_ranks, 
    special_tokens={ 
        **cl100k_base._special_tokens, 
        "<|im_start|>": 100264, 
        "<|im_end|>": 100265
    } 
) 

tokens = enc.encode( 
    "<|im_start|>user\nHello<|im_end|><|im_start|>assistant",  
    allowed_special={"<|im_start|>", "<|im_end|>"} 
) 

assert len(tokens) == 7 
assert tokens == [100264, 882, 198, 9906, 100265, 100264, 78191]

后续步骤