Python调用GPT-3.5和GPT-4的API
发布日期:2023/12/12 16:27:36 浏览量:
Python调用GPT-3.5和GPT-4的API代码
import openai
import io
import sys
import requests
import json
# 改变标准输出的默认编码
sys.stdout = io.TextIOWrapper(sys.stdout.buffer, encoding=’utf8’)
def gpt35_chat_response(prompt, api_key):
headers = {
’Authorization’: f’Bearer {api_key}’,
’Content-Type’: ’application/json’
}
data = {
"model": "gpt-3.5-turbo", # 更改为 GPT-3.5 模型名称 #text-davinci-003
"messages": [
{"role": "system", "content": "You are a helpful assistant."},
{"role": "user", "content": prompt}
]
}
response = requests.post(
’https://api.openai.com/v1/chat/completions’,
headers=headers,
data=json.dumps(data)
)
if response.status_code == 200:
return response.json()[’choices’][0][’message’][’content’]
else:
return f"Error: {response.text}"
def gpt4_chat_response(prompt, api_key):
headers = {
’Authorization’: f’Bearer {api_key}’,
’Content-Type’: ’application/json’
}
data = {
"model": "gpt-4",
"messages": [
{"role": "system", "content": "You are a helpful assistant."},
{"role": "user", "content": prompt}
]
}
response = requests.post(
’https://api.openai.com/v1/chat/completions’,
headers=headers,
data=json.dumps(data)
)
if response.status_code == 200:
return response.json()[’choices’][0][’message’][’content’]
else:
return f"Error: {response.text}"
# 示例用法
api_key = "sk-*********************************************" # 替换为你的 API 密钥
# 初始提示文本
prompt = "你好,你是哪个版本的模型?"
print(gpt4_chat_response(prompt, api_key))
print(gpt35_chat_response(prompt, api_key))
业务实施流程
马上咨询: 如果您有业务方面的问题或者需求,欢迎您咨询!我们带来的不仅仅是技术,还有行业经验积累。
QQ: 39764417/308460098 Phone: 13 9800 1 9844 / 135 6887 9550 联系人:石先生/雷先生