【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()
相关推荐
前端阿彬2 小时前
我用AI做了个微信小游戏-上线了
gpt·ai编程·gemini
ofoxcoding6 小时前
2026 轻量模型 API 实测:GPT-5.5 Nano、Gemini 3.1 Flash、Haiku 4.5 延迟与成本横评
运维·gpt·ai
@大迁世界12 小时前
GPT-5.5 和 Opus 4.7,到底该用谁?
gpt
码农阿强12 小时前
GPT-5.5 与 GPT-5.5-Pro 技术差异及接口接入实践
人工智能·gpt·ai·aigc·ai编程·ai写作·gpu算力
2601_9577875512 小时前
基于 4SAPI 的 GPT-Codex 本地部署与全功能配置实战教程
人工智能·gpt·ai编程·ai应用开发
crossoverJie1 天前
OpenAI 三连发:GPT-5.5、Codex移动端、DeployCo,AI编程进入新阶段
人工智能·gpt·ai编程
yaodong5181 天前
多模态处理能力:GPT-5.5 vs Grok4
gpt
~黄夫人~1 天前
常见AI专有名词解释(用公司管理的方式理解 AI 世界)
人工智能·gpt·ai
应用市场2 天前
Android分区表深度解析:GPT、各分区作用与布局实战
android·gpt
Resistance丶未来2 天前
【手把手详细教程】 Trae AI和Vscode~使用第三方中转API配置Claude ,GPT,Gemini等大模型教程
人工智能·gpt