Advertisement

了解如何使用 GPT-35-Turbo 和 GPT-4 模型

阅读量:

GPT-35-Turbo 和 GPT-4 模型基于对话接口进行了改进。 与先前版本的 GPT 模型(如 GPT-3)相比,在行为上存在显著差异。 前者的操作模式是以文本输入和文本输出为基础:它们接受一个提示信息并生成一个补充内容添加到提示末尾。 相反地,GPT-35-Turbo 和 GPT-4 则是通过接受对话回合并生成相应消息来工作的。 它们通常需要用户提供类似聊天记录的具体输入脚本,并通过交互生成补充信息。 而值得注意的是,这种交互模式最初设计用于多轮对话交流但发现其也适用于非实时交流场景。

在 Azure OpenAI 中,你有两种不同的方案与这两种类型的模型交互:

  • 聊天补全 API。
  • 使用聊天标记语言 (ChatML) 的补全 API。

聊天补全功能是一种专为与GPT-35-Turbo和GPT-4等先进AI模型互动设计的新功能。通过此功能成为获取这些模型的首选途径。这也是获取新版GPT-4模型的独特途径。

尽管 ChatML 所使用的补全 API与常见的 text-davinci-002 模型所使用的相同。然而这种特定提示格式被定义为名为 ChatML 的标记语言。该系统相比专门设计的专用聊天补单API提供了更为受限的访问权限,并在功能上还需进行额外的安全性验证才能使用。它仅限于 gpt-35-turbo 模型,并且其基本架构可能会随着时间推移而发生更新。

本文旨在教导您如何开始使用 GPT-35-Turbo 和 GPT-4 模型。 请务必采用本文所述的技术来获取最佳效果。 若试图以旧模型系列交互的方式尝试与新模型互动,则通常会导致冗长的响应且效果不佳。

使用 GPT-3.5-Turbo 和 GPT-4 模型

以下代码展示了如何通过聊天补全API使用GPT-3.5-Turbo和GPT-4模型的基本方法。作为新手,在编程中首次接触这些模型时,请参考GPT-3.5-Turbo和GPT-4快速入门教程开始学习。

复制代码
 import os

    
 import openai
    
 openai.api_type = "azure"
    
 openai.api_version = "2023-05-15" 
    
 openai.api_base = os.getenv("AZURE_OPENAI_ENDPOINT")  # Your Azure OpenAI resource's endpoint value.
    
 openai.api_key = os.getenv("AZURE_OPENAI_API_KEY")
    
  
    
 response = openai.ChatCompletion.create(
    
     engine="gpt-35-turbo", # The deployment name you chose when you deployed the GPT-3.5-Turbo or GPT-4 model.
    
     messages=[
    
     {"role": "system", "content": "Assistant is a large language model trained by OpenAI."},
    
     {"role": "user", "content": "Who were the founders of Microsoft?"}
    
     ]
    
 )
    
  
    
 print(response)
    
  
    
 # To print only the response content text:
    
 # print(response['choices'][0]['message']['content'])
    
    
    
    
    代码解读

输出

为便于阅读而人为添加的 JSON 格式。

复制代码
 {

    
   "choices": [
    
     {
    
       "finish_reason": "stop",
    
       "index": 0,
    
       "message": {
    
     "content": "The founders of Microsoft are Bill Gates and Paul Allen. They co-founded the company in 1975.",
    
     "role": "assistant"
    
       }
    
     }
    
   ],
    
   "created": 1679014551,
    
   "id": "chatcmpl-6usfn2yyjkbmESe3G4jaQR6bsScO1",
    
   "model": "gpt-3.5-turbo-0301",
    
   "object": "chat.completion",
    
   "usage": {
    
     "completion_tokens": 86,
    
     "prompt_tokens": 37,
    
     "total_tokens": 123
    
   }
    
 }
    
  
    
    
    
    
    代码解读

注意

以下不可用于新的 GPT-35-Turbo 和 GPT-4 模型的参数包括:logprobs、best_of 以及 echo。一旦你配置了这些参数中的任何一个就会触发错误。

每个回复都包含 finish_reasonfinish_reason可能的值为:

  • stop:API 返回了完整的模型输出。
  • length:受限于max_tokens参数或标记限制因素的影响,导致模型无法生成完整的结果。
  • content_filter:基于内容筛选器的设置过滤掉了相关内容。
  • null:当前API回复的状态为正在进行中/未完成状态。

建议将参数 max_tokens 调整为略微超出常规设定的水平,并选择 300 或 500 这两个具体的数值范围作为参考标准。 这种做法能够有效防止模型在消息结束前提前终止生成文本内容。

模型版本控制

注意

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

不同于以往的GPT-3和GPT-3.5系列模型,《gpt-35-turbo》及其GPT-4系列(包括GPT-4和GPT-4 32k参数版本)将持续进行更新。在部署这些模型的过程中,请明确指定其相应的模型版本信息。

在我们的模型页面中查找这些模型的停用日期。

使用聊天补全 API

OpenAI 开发了 GPT-35-Turbo 和 GPT-4 模型,并通过接受对话形式的输入来进行交互。
消息参数用于提取消息对象数组,并根据角色对对话进行排序。
当使用 Python API 时,请确保采用字典列表的形式。

基本的聊天补全的格式如下所示:

复制代码
 {"role": "system", "content": "Provide some context and/or instructions to the model"},

    
 {"role": "user", "content": "The users messages goes here"}
    
    
    
    
    代码解读

一个示例答案后跟一个问题的对话如下所示:

复制代码
 {"role": "system", "content": "Provide some context and/or instructions to the model."},

    
 {"role": "user", "content": "Example question goes here."},
    
 {"role": "assistant", "content": "Example answer goes here."},
    
 {"role": "user", "content": "First question/message for the model to actually respond to."}
    
    
    
    
    代码解读

系统角色

数组的开头由系统角色(也被称作系统消息)构成。 该消息被用来作为模型的初始设定依据。 如以下内容所示:

  • 助手的简明扼�地概述一下
  • 助手的独特之处
  • 明确指示
  • 所需数据来源及辅助信息

允许根据用例自定义系统角色或者仅需提供基础信息。其中系统角色和消息并非必要但推荐至少提供一个基础描述以便获得最佳效果

消息

在系统角色之后,可以在用户和助手之间加入一系列消息。

复制代码
     {"role": "user", "content": "What is thermodynamics?"}
    
    
    代码解读

为了使模型能够及时响应,在用户的最后一条消息中应当明确指示这已经是本轮由系统回应的时候。 此外,在用户与助手之间传递若干示例信息后,则可实现少数据学习的目的。

消息提示示例

以下内容涵盖了可用于 GPT-35-Turbo 和 GPT-4 模型的各种提示样式。这些示例仅作参考用途,建议你可以尝试使用不同的提示来为你的应用场景定制化行为。

基本示例

为了使 GPT-35-Turbo 的行为与 OpenAI 的交互模式相仿, 可以配置基础交互消息, 例如'该助手基于 OpenAI 的训练数据构建'

复制代码
 {"role": "system", "content": "Assistant is a large language model trained by OpenAI."},

    
 {"role": "user", "content": "Who were the founders of Microsoft?"}
    
    
    
    
    代码解读

说明的示例

在特定情况下

复制代码
 {"role": "system", "content": "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. "},
    
 {"role": "user", "content": "When are my taxes due?"}
    
    
    
    
    代码解读

使用数据进行验证

可以在对话过程中通过系统消息传递相关信息,并根据需要调整后续交互内容。 当仅需少量信息时,可以直接将这些信息嵌入到系统消息中以便模型更好地理解对话背景。 如果你有大量需要模型关注的数据,则可以使用[嵌入]... 或 [Azure AI 搜索]... 等产品在查询时检索最相关的信息以便快速获取所需数据。

复制代码
 {"role": "system", "content": "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'.

    
   3. 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."
    
 },
    
 {"role": "user", "content": "What is Azure OpenAI Service?"}
    
    
    
    
    代码解读

使用聊天补全进行少样本学习

此外还可以通过模型提供少样本学习的具体示例以促进其应用效果

这一实例仅是GPT-35-Turbo与GPT-4在小样本学习领域中的一个应用案例。 为了找到最适合您的具体情况的最佳方案,请不妨探索其他可能性。

复制代码
 {"role": "system", "content": "Assistant is an intelligent chatbot designed to help users answer their tax related questions. "},

    
 {"role": "user", "content": "When do I need to file my taxes by?"},
    
 {"role": "assistant", "content": "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."},
    
 {"role": "user", "content": "How can I check the status of my tax refund?"},
    
 {"role": "assistant", "content": "You can check the status of your tax refund by visiting https://www.irs.gov/refunds"}
    
    
    
    
    代码解读

将聊天补全用于非聊天场景

聊天补全 API 设计用于多回合对话,但也适用于非聊天场景。

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

复制代码
 {"role": "system", "content": "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": ""
    
 }"},
    
 {"role": "user", "content": "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?"}
    
    
    
    
    代码解读

创建基本聊天循环

到目前为止为止这些例子展示了与聊天补全API交互的基本流程 此例子展示了如何构建对话循环以实现以下功能

到目前为止为止这些例子展示了与聊天补全API交互的基本流程 此例子展示了如何构建对话循环以实现以下功能

  • 持续地从控制台接收输入数据,并按规范形式整合进消息列表里作为用户的展示内容。
    • 在屏幕上输出响应指令后进行规范化处理并加入消息序列用于反映助手的功能作用。

每当提出新的问题时,在每次提出新问题的时候,
系统会自动发送到目前为止运行的所有对话脚本,
并一并包含最新的提问内容。
然而,
因为模型缺乏内存,
系统必须在每一次对话中单独发送最新的对话内容,
否则会导致模型无法理解整个对话的历史和关联性。

复制代码
 import os

    
 import openai
    
 openai.api_type = "azure"
    
 openai.api_version = "2023-05-15" 
    
 openai.api_base = os.getenv("AZURE_OPENAI_ENDPOINT")  # Your Azure OpenAI resource's endpoint value.
    
 openai.api_key = os.getenv("AZURE_OPENAI_API_KEY")
    
  
    
 conversation=[{"role": "system", "content": "You are a helpful assistant."}]
    
  
    
 while True:
    
     user_input = input()      
    
     conversation.append({"role": "user", "content": user_input})
    
  
    
     response = openai.ChatCompletion.create(
    
     engine="gpt-35-turbo", # The deployment name you chose when you deployed the GPT-35-turbo or GPT-4 model.
    
     messages=conversation
    
     )
    
  
    
     conversation.append({"role": "assistant", "content": response["choices"][0]["message"]["content"]})
    
     print("\n" + response['choices'][0]['message']['content'] + "\n")
    
    
    
    
    代码解读

运行上述代码时,请您查看会话框以观察到空白界面。 在会话框中键入第一个查询项后按回车响应即可。 回车响应后可反复执行此操作持续输入更多查询项。

管理对话

该示例会持续运行直至模型达到标记上限。 每次提问并收到回答后, messages列表中的条目数量会有所增长。 各版本如GPT-35-Turbo、GPT-4及GPT-4-32K的最大标记数分别为4096、8192至32768, 其中GPT-35-Turbo的上限较小, 而GPT-4及其变种则拥有更大的设置空间, 适用于不同场景下的处理需求。 这些设定既涵盖发送消息的数量也涉及模型回复中的标记计数, 因此在与 max_tokens 参数配合使用时需确保整体不超过指定限制, 否则系统将返回错误信息。

你需要遵循一定的规范来执行提示和补全操作,并且使其不超过标记数量。 这表明,在处理长对话时需要实时监控标记的数量,并仅传递符合规定的提示信息。

注意

请务必坚持执行以下措施:无论是在哪个模型版本中,请确保不会超出输入令牌的数量上限。

以下是用于展示简单对话流程的一个代码片段。该技术采用了OpenAI的tiktoken库来管理4096标记计数的过程。

此代码采用 tiktoken 库的 0.5.1 版本(具体而言是主开发分支)。若需升级现有版本,请执行以下操作:运行命令 pip install tiktoken --upgrade 以获取最新更新。

复制代码
 import tiktoken

    
 import openai
    
 import os
    
  
    
 openai.api_type = "azure"
    
 openai.api_version = "2023-05-15" 
    
 openai.api_base = os.getenv("AZURE_OPENAI_ENDPOINT")  # Your Azure OpenAI resource's endpoint value.
    
 openai.api_key = os.getenv("AZURE_OPENAI_API_KEY")
    
   10. system_message = {"role": "system", "content": "You are a helpful assistant."}
    
 max_response_tokens = 250
    
 token_limit = 4096
    
 conversation = []
    
 conversation.append(system_message)
    
   16. def num_tokens_from_messages(messages, model="gpt-3.5-turbo-0613"):
    
     """Return the number of tokens used by a list of messages."""
    
     try:
    
     encoding = tiktoken.encoding_for_model(model)
    
     except KeyError:
    
     print("Warning: model not found. Using cl100k_base encoding.")
    
     encoding = tiktoken.get_encoding("cl100k_base")
    
     if model in {
    
     "gpt-3.5-turbo-0613",
    
     "gpt-3.5-turbo-16k-0613",
    
     "gpt-4-0314",
    
     "gpt-4-32k-0314",
    
     "gpt-4-0613",
    
     "gpt-4-32k-0613",
    
     }:
    
     tokens_per_message = 3
    
     tokens_per_name = 1
    
     elif model == "gpt-3.5-turbo-0301":
    
     tokens_per_message = 4  # every message follows <|start|>{role/name}\n{content}<|end|>\n
    
     tokens_per_name = -1  # if there's a name, the role is omitted
    
     elif "gpt-3.5-turbo" in model:
    
     print("Warning: gpt-3.5-turbo may update over time. Returning num tokens assuming gpt-3.5-turbo-0613.")
    
     return num_tokens_from_messages(messages, model="gpt-3.5-turbo-0613")
    
     elif "gpt-4" in model:
    
     print("Warning: gpt-4 may update over time. Returning num tokens assuming gpt-4-0613.")
    
     return num_tokens_from_messages(messages, model="gpt-4-0613")
    
     else:
    
     raise NotImplementedError(
    
         f"""num_tokens_from_messages() is not implemented for model {model}. See https://github.com/openai/openai-python/blob/main/chatml.md for information on how messages are converted to tokens."""
    
     )
    
     num_tokens = 0
    
     for message in messages:
    
     num_tokens += tokens_per_message
    
     for key, value in message.items():
    
         num_tokens += len(encoding.encode(value))
    
         if key == "name":
    
             num_tokens += tokens_per_name
    
     num_tokens += 3  # every reply is primed with <|start|>assistant<|message|>
    
     return num_tokens
    
  
    
 while True:
    
     user_input = input("")     
    
     conversation.append({"role": "user", "content": user_input})
    
     conv_history_tokens = num_tokens_from_messages(conversation)
    
  
    
     while conv_history_tokens + max_response_tokens >= token_limit:
    
     del conversation[1] 
    
     conv_history_tokens = num_tokens_from_messages(conversation)
    
  
    
     response = openai.ChatCompletion.create(
    
     engine="gpt-35-turbo", # The deployment name you chose when you deployed the GPT-35-Turbo or GPT-4 model.
    
     messages=conversation,
    
     temperature=0.7,
    
     max_tokens=max_response_tokens,
    
     )
    
  
    
     conversation.append({"role": "assistant", "content": response['choices'][0]['message']['content']})
    
     print("\n" + response['choices'][0]['message']['content'] + "\n")
    
    
    
    
    代码解读

在此示例案例中,在达到标记计数时会删除对话脚本中的最初消息。 为了提升效率,在实现过程中采用了del函数而非pop()函数,并从索引1的位置开始操作以保留系统消息的同时仅去除用户或助手的消息输出。 随着时间的推移这种基于逻辑的操作可能会导致对话质量逐渐下降因为模型随着时间推移将会逐渐丧失对对话早期信息的理解和上下文维护能力

另一种策略是将对话持续时间限定在最大标记长度或特定回合内进行。
当模型达到最大标记长度时,在允许继续对话的情况下(即模型已失去上下文),可以建议用户开始一个新的对话并清空消息列表以启动新的会话。

在之前的演示中展示了标记计数模块作为OpenAI 指南示例的一个简化版。

后续步骤

使用聊天模型

重要

此 GPT-35-Turbo 模型与补充完整端点协同作用的功能目前处于试用阶段。鉴于可能存在 ChatML 语法基础的变化趋势,我们郑重推荐采用聊天补充 API 或者补充完整终端作为主要工具。推荐采用聊天补充 API 作为 GPT-35-Turbo 模型的交互界面。仅限于通过聊天补充 API 方式才能调用 GPT-4 模型。

此代码片段展示了通过 ChatML 实现 GPT-35-Turbo 模型的基础方法。如果你是首次以编程方式接触这些模型,请参考 GPT-35-Turbo 和 GPT-4 快速入门教程以获得基础指导。

复制代码
 import os

    
 import openai
    
 openai.api_type = "azure"
    
 openai.api_base = "https://{your-resource-name}.openai.azure.com/"
    
 openai.api_version = "2023-05-15"
    
 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 模型:"logprobs"、"best_of" 以及 "echo"。一旦任何该列表中的参数被启用,系统将返回错误信息。

<|im_end|> 标记被用作消息结束的指示。 建议将其作为终止序列包含在内以确保模型在到达消息末尾时停止生成文本。 有关特殊标记的详细信息,请参阅聊天标记语言 (ChatML) 部分

建议将max_tokens稍微超出常规数值,并如300或500所示设置具体值。这将确保模型在接收到消息末尾前不会提前终止生成文本

模型版本控制

注意

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

相较于现有的 GPT-3 和 GPT-3.5 模型,《gpt-35-turbo》系列以及 GPT-4 和 GPT-4 系列将持续进行更新。在部署这些模型时,请注意需指定具体模型版本以确保正确运行。

请查阅我们的模型页面以获取这些模型的退役日期。

使用聊天标记语言 (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中的相关资料:
    • 包括但不限于:数据集 D 和模型 M
    • 其他相关参数可根据需求补充

为您的用例自定义系统消息是一个不错的选择,您也可以仅设置基础的消息来满足需求.需要注意的是,系统消息并不是必须的,但建议您至少添加一条基础的消息,以便获得最佳体验.

消息

在系统消息之后,在用户和助手之间可以添加一系列的信息。每个信息条目都需要以特定的开始标记<|im_start|来标识,并在结束时使用特定结束标记<|im_end|

复制代码
 <|im_start|>user

    
 What is thermodynamics?
    
 <|im_end|>
    
    
    
    
    代码解读

为了使模型能够发出回应, 提示应以<|im_start|>assistant标记结尾, 表明轮到助手进行回复. 也可在提示中包含用户与助手之间的交流内容, 作为少样本学习的一种方法.

提示示例

以下部分展示了不同提示样式的实例用于GPT-35-Turbo和GPT-4模型。 这些案例仅作启发,请尝试使用不同的提示以自定义行为。

以下部分展示了不同提示样式的实例用于GPT-35-Turbo和GPT-4模型。 这些案例仅作启发,请尝试使用不同的提示以自定义行为。

基本示例

如果你希望 GPT-35-Turbo 和 GPT-4 模型的行为与 chat.openai.com 类似,并且想要模拟 OpenAI 的 assistant 角色,请设置基础交互信息如"助手基于 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协同作用时,在提示部分累计使用的总标志数目不应超过这一设定上限;否则将会触发错误信息。

你需要负有义务确保指示和补充操作在其标记界限内运行。 这表示,在处理较长对话时,请追踪当前标记的数量,并且只将包含不超过标记限制的提示传递给模型。

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

复制代码
 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 = "2023-05-15" 
    
 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'])
    
    
    
    
    代码解读

控制在标记限制之下

受标记限制影响的基本途径是在达到标记限制时删除对话中早期消息。

可以选择尽量多地包含标记的同时维持在限制内,并且还可以始终保持一定的数量(前提是这些消息能够维持在限制内)。请注意较长提示通常会消耗更多时间并带来更高的成本。

通过该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]
    
    
    
    
    代码解读

全部评论 (0)

还没有任何评论哟~