Python調(diào)用GPT-3.5和GPT-4的API
發(fā)布日期:2023/12/12 16:27:36 瀏覽量:
Python調(diào)用GPT-3.5和GPT-4的API代碼
import openai
import io
import sys
import requests
import json
# 改變標(biāo)準(zhǔn)輸出的默認(rèn)編碼
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 = "你好,你是哪個(gè)版本的模型?"
print(gpt4_chat_response(prompt, api_key))
print(gpt35_chat_response(prompt, api_key))
馬上咨詢: 如果您有業(yè)務(wù)方面的問題或者需求,歡迎您咨詢!我們帶來的不僅僅是技術(shù),還有行業(yè)經(jīng)驗(yàn)積累。
QQ: 39764417/308460098 Phone: 13 9800 1 9844 / 135 6887 9550 聯(lián)系人:石先生/雷先生