【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()
相关推荐
u01027894017 小时前
GPT-Image-2 图片编辑:一键改色换背景,AI视觉创作的效率革命
人工智能·gpt·ai作画·aigc
南方程序猴2 天前
我把 Node.js、npm 和 Codex CLI 全卸了,重新测了一遍 Windows 一键安装
人工智能·gpt·ai·ai编程
南方程序猴2 天前
Windows一键安装Codex所有环境
人工智能·gpt·ai·chatgpt·ai编程
王莹月2 天前
nano banana pro 怎么用?生图接口返回的图别直接存链接:nano banana pro / gpt-image-2 出图结果的落库与转存
gpt·ai·chatgpt·ai作画·aigc·agi
A小码哥2 天前
Qwen3.8-Max、GPT-5.6 以及 Claude (Opus 5 / Fable 5)的横向对比
gpt
tanglinS2 天前
工业陶瓷榜单:国内精密工业陶瓷零部件供应商综合选型参考
大数据·运维·人工智能·gpt·材质
天天有money2 天前
Claude 中转站用于报告生成:会议纪要、周报和项目复盘怎么提效
gpt·ai·chatgpt
YH55269842 天前
如何评价GPT-5.6Luna免费不限量,后续基础大模型都会走向免费吗?
人工智能·gpt·chatgpt
JJJennie7773 天前
ChatGPT 更新 GPT-5.6 Sol,免费用户将可无限文本聊天
人工智能·gpt·chatgpt
dunge20263 天前
2026年8月更新:ChatGPT与Codex开发实践——从工具使用到AI工程工作流,开发者如何建立长期生产力体系(GPT-5.6技术分享)
人工智能·gpt·chatgpt