使用Python调用ChatGPT API_python调用api函数
当前ChatGPT使用gpt-3.5和gpt-4等语言大模型,提供了强大的文本交互功能。用户也可以使用gpt-3.5或gpt-4提供的API接口构建自己的应用。本文简单的介绍一下使用Python调用ChatGPT API时的一些知识。
安装openai库
openai库提供了方便的操作chatgpt的接口,使用pip命令安装它
pip install --upgrade openai
使用openai库调用ChatGPT API
import openai
openai.api_key = "你的openai key"
MODEL = "gpt-3.5-turbo"
response = openai.ChatCompletion.create(
model=MODEL,
messages=[
{"role": "system", "content": "你是一个编程助手"},
{"role": "user", "content": "你好."},
{"role": "assistant", "content": "有什么能帮你的?"},
{"role": "user", "content": "我想学习NLP自然语言处理"},
],
temperature=0,
n=1,
stream=False
)
result=response["choices"][0]["message"]["content"]
print(result)
你需要使用
openai.ChatCompletion.create函数调用ChatGPT API,这和之前调用旧模型的方式有一些差别,主要参数介绍如下:
- api_key:你需要在openAI官方网站上生成你的api_key。
- Model:模型的名字你可以使用gpt-3.5-turbo, gpt-4, gpt-4-0314等
- messages:messages参数是一个询问信息的列表数组,数组中每个对象字典包含两个key
role:信息的角色,可以是system,user,assitant三种角色之一,其中system 用于定义接口的行为,比如「你是一个写作助手」
content:提问的消息内容
例如:
messages=[
{"role": "system", "content": "你是一个编程助手"},
{"role": "user", "content": "你好."},
{"role": "assistant", "content": "有什么能帮你的?"},
{"role": "user", "content": "我想学习NLP自然语言处理"},
],
每次提交的messages消息是本次对话的消息上下文,这样gpt就可以有历史知识,具体提交多少历史上下文,编程时可以灵活指定,上下文越多意味着费用更高,响应速度更慢。
一般来说一次会话messages列表中一般是以system角色消息开始(可选非必须),定义gpt的行为,然后在以user和assistant角色消息交替循环作为历史上下文。
- temperature: 温度系数0-1 ,越靠近0代表gpt思维越发散,越具有创造性
- n=1 模型返回回答数量,这对应请求的响应数据choices数组的大小,默认是1。
- stream=False 是否启用流式回答,默认是true意味着回答的内容会一次性全部返回,
如果设置为True,那么gpt的响应会分批返回,在chatgpt官方网页体验中采用的是这种方 式,形成了打字机的效果。
此外
openai.ChatCompletion.create还有如下的可选参数
1. max_tokens(可选参数):生成的响应中最多包含的token数。
2. stop(可选参数):指定生成文本时要停止的字符串或单词。这可以是单个字符串,也可以是字符串列表。例如,如果您想要停止生成文本、并在获得一个问候后停止响应,您可以将其设置为“hello”。
3. presence_penalty(可选参数):用于控制生成的响应中重复出现单次的惩罚系数,该系数越高则重复出现单次的概率越低。默认值为0。
4. frequency_penalty(可选参数):用于控制生成的响应中对不常见单次的惩罚系数,该系数越高则出现不常见单次的概率越低。默认值为0。
响应数据的格式如下所示:
{
"choices": [{
"finish_reason": "stop",
"index": 0,
"message": {
"content": "Orange who?",
"role": "assistant"
}}],
"created": 1679718435,
"id": "chatcmpl-6xpmlDodtW6RwiaMaC1zhLsR8Y1D3",
"model": "gpt-3.5-turbo-0301",
"object": "chat.completion",
"usage": {
"completion_tokens": 3,
"prompt_tokens": 39,
"total_tokens": 42
}}
响应数据主要参数解释如下:
id:本次请求的ID
usage:本地调用请求的token数,响应的token数,本次会话总的token数
choices:回答信息的结果列表,取决请求参数n,默认请求参数n=1,choice列表中默认一个回答,数组中每个回答的参数包括如下内容:
message:回答的消息内容,包括role和content两个角色,gpt的回答role角色值是assistant
finish_reason:模型返回的原因,例如stop,length,正常返回值是stop,超过最大max_tokens 表示信息被截断,返回length
index:本条回答在消息列表中的次序
如果你要提取默认一个回答的内容使用如下的代码
response['choices'][0]['message']['content']
system角色信息
system角色信息用来设置gpt不同的表现行为和个性,按照官方的介绍gpt3.5对system角色设置的信息,并不敏感,建议将重要的信息放在user角色提问信息中。而在gpt4中system角色信息有更重要的影响。
例如:
response = openai.ChatCompletion.create(
model=MODEL,
messages=[
{"role": "system", "content": "你是你个语音助手,请每次用简短的话回答问题"},
{"role": "user", "content": "请告诉我如何成为一个超级英雄"},
])
print(response["choices"][0]["message"]["content"])
鼓励模型
在某些情况下在模型给出你响应信息后,对GPT说出”你的回答很棒“之类鼓励的话,会提高模型回答的准确性,难道gpt真的有感情吗。
计算tokens
对gpt的提问会被转化为token序列,token的数量会影响费用,响应速度,和回答的字数。在gpt3.5中每次问答最大的token数量是4096个,而在gpt4中是8192个,注意这里的最大数量指的请求和回答的token的总数。这意味如果你的提问的问题的token数量非常大,会极大的影响模型回答的字数。
def num_tokens_from_messages(messages, model="gpt-3.5-turbo-0301"):
"""Returns 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 == "gpt-3.5-turbo":
print("Warning: gpt-3.5-turbo may change over time. Returning num tokens assuming gpt-3.5-turbo-0301.")
return num_tokens_from_messages(messages, model="gpt-3.5-turbo-0301")
elif model == "gpt-4":
print("Warning: gpt-4 may change over time. Returning num tokens assuming gpt-4-0314.")
return num_tokens_from_messages(messages, model="gpt-4-0314")
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 model == "gpt-4-0314":
tokens_per_message = 3
tokens_per_name = 1
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