环境变量设置
.env文件中配置GPT环境变量
api_key="你的GPT-API-KEY"
url=https://ai-proxy.ksord.com/wps.openai.azure.com/openai/deployments/gpt-4-32k/chat/completions?api-version=2023-09-01-preview
主调用方法
一般需要先安装load_dotenv库:
pip install load_dotenv
import requests
import os
from dotenv import load_dotenv
# 获取env文件中的环境变量
load_dotenv()
# 环境变量赋值
endpoint = os.getenv("url")
api_key = os.getenv("api_key")
# 封装GPT请求方法
def get_completion(messages, model="gpt-4-32k"):
headers = {
"Content-Type": "application/json",
"api-key": api_key,
}
payload = {"model": model, "messages": messages, "temperature": 0.5, "top_p": 1, "frequency_penalty": 0, "presence_penalty": 0, "stop": None}
response = requests.post(endpoint, headers=headers, json=payload, stream=True)
try:
# 提取GPT返回的结果信息
return response.json()["choices"][0]["message"]["content"]
except Exception as e:
# 请求报错时,返回错误原因
print(response.json())
raise e
# 赋初值,也可设为空List
messages = [{"role": "system", "content": "You are a helpful assistant."}]
# 设置传入message值为input型
# 设置特殊指令break
# 打印返回结果
while True:
message = input("User: ")
if message.lower() in ("quit", "exit"):
break
messages.append({"role": "user", "content": message})
anwser = get_completion(messages)
print(f"Bot: {anwser}")
messages.append({"role": "assistant", "content": anwser})