3.聊天标记语言 (ChatML),ChatML 将文本作为消息序列以及元数据一起提供给 ChatGPT API。这与标准的 ChatGPT 相反,后者将原始文本表示为一系列令牌。例如,单词“fantastic”将被拆分为令牌“fan”、“tas”和“tic”,以及为了防止安全漏洞和滥用途径即时注入攻击,作为开发者,您可以更有效地防范这些种类的攻击(使用角色:System,assistant,user等权限)。
pip install --upgrade openai准备工作完成,我们开始编写代码
#堆代码 duidaima.com # main.py import openai openai.api_key = "你的Key" chat_completion = openai.ChatCompletion.create( model="gpt-3.5-turbo", messages=[ # system message first, it helps set the behavior of the assistant {"role": "system", "content": "You are a helpful assistant."}, # I am the user, and this is my prompt {"role": "user", "content": "What's the best star wars movie?"}, # we can also add the previous conversation # {"role": "assistant", "content": "Episode III."}, ], ) print(chat_completion.choices[0].message.content)messages 是一个字典列表,包含 role 和 content 两个键。role 可以是 system,用于设置聊天机器人的行为;user 表示与聊天机器人进行交互的用户(也就是我们自己);assistant 则表示聊天机器人本身。在 content 中,我们放置我们的文本内容。
ChatGpt的回复:
As an AI language model, I do not have personal opinions or preferences. However, many people consider "The Empire Strikes Back" to be the best Star Wars movie due to its engaging storyline, iconic characters, and memorable twists.
import openai import os #堆代码 duidaima.com openai.api_key = "你的Key" messages = [ # 系统消息应该在最前面,它有助于设定助手的行为 {"role": "system", "content": "You are a helpful assistant."}, ] while True: message = input(": ") if message: # 检查用户是否想退出程序 if message.lower() in ["exit", "quit"]: break messages.append( {"role": "user", "content": message}, ) chat_completion = openai.ChatCompletion.create( model="gpt-3.5-turbo", messages=messages ) # get the reply reply = chat_completion.choices[0].message.content print(f": {reply}") messages.append({"role": "assistant", "content": reply})接下来我们运行下程序体验下,如下截图所示: