【GPT】基于GPT_API_free做一个自己的gpt

最终效果

项目背景

秉持能免费就绝不花钱的原则,基于github项目GPT_API_free获取的gpt apikey。下面是简单的代码

python 复制代码
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()
相关推荐
Aision_14 小时前
Agent 为什么需要 Checkpoint?
人工智能·python·gpt·langchain·prompt·aigc·agi
寺中人1 天前
Windows系统的GPT磁盘分区
windows·gpt·数据恢复·工具·winhex·硬盘修复
kyriewen2 天前
GPT-5.5 全员白嫖,DeepSeek 估值 3000 亿,但 Claude 今天被请喝茶了
gpt·claude·deepseek
向量引擎2 天前
为什么大厂做 RAG,都要加一层向量引擎中转站?
人工智能·gpt·aigc·api·key
奔跑吧树袋熊2 天前
Opus 4.7 + GPT-5.5“双核驱动”——2026最强AI编程工作流实测
gpt·ai编程
多年小白2 天前
【盘前分析】2026年5月6日(周三)节后首日开盘指南
科技·gpt·百度·ai
-嘟囔着拯救世界-2 天前
手把手教你低成本搭建 GPT-image-2 工作流,再也不愁没有好配图了!
人工智能·gpt·ai·ai作画·aigc·gpt-image-2
zhuiyisuifeng2 天前
2026年AI图像生成:色彩语义理解新突破
人工智能·gpt·计算机视觉