最终效果

项目背景
秉持能免费就绝不花钱的原则,基于github项目GPT_API_free获取的gpt apikey。下面是简单的代码
import json
import os
import requests
openai_url = os.getenv("openaiproxy")
openai_apikey = os.getenv("openaikey")
# 初始化上下文
conversations_his = []
# 添加上下文对话添加
def add_conversations_his(role,content):
conversations_his.append({"role": role, "content": content})
def generate_code(user_input:str):
add_conversations_his("user", user_input)
header = {
"Content-Type": "application/json",
"Authorization": "Bearer " + openai_apikey
}
body = {
"model": "gpt-4o-mini",
"messages": conversations_his
}
# ai返回的信息
resp = requests.post(url=openai_url,headers=header,data=json.dumps(body))
# 提取ai恢复中的msg并将其添加到历史对话中
ai_msg = resp.json()["choices"][0]["message"]["content"]
add_conversations_his("assistant",ai_msg)
if resp.status_code == 200:
# print(f"历史对话: {conversations_his}")
return ai_msg
else:
print(f"请求失败: {resp.status_code}")
def conversations():
# with open("prompt\\system_prompt","r",encoding="utf-8") as f:
# content =f.read()
# add_conversations_his("system",content)
while True:
user_msg = input("You: ")
if user_msg.lower() in ["退出","exit","quit","q"]:
break
ai_respmsg = generate_code(user_msg)
print(f"GPT: {ai_respmsg}")
if __name__ == "__main__":
conversations()
![[图解]SysML和EA建模住宅安全系统-活动作为块](https://i-blog.csdnimg.cn/direct/927713efd37a467eb5e18f3cd5af83af.png)



![[Algorithm][综合训练][字符编码][最少的完全平方数][游游的字母串]详细讲解](https://i-blog.csdnimg.cn/direct/580005b319a34a31bf66c8eff2daa196.png)




![C++map容器中operator[ ]的实现原理](https://i-blog.csdnimg.cn/direct/18e0925791b54b1d874646a9914fd428.png)









