【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()
相关推荐
神奇霸王龙20 小时前
GPT-Image-2 角色一致性屠榜:2026 五款图生图模型 IP 漫剧实测
人工智能·gpt·tcp/ip·ai·ai作画·prompt·音视频
库拉大叔20 小时前
写小说谁家强?GPT-5.6、Claude 4.8 Opus、Gemini 3.5文学素养硬核横评
人工智能·gpt·aigc
OpenCSG2 天前
GPT-5.6 深夜正式上线:下一代模型能力升级,AI Agent 进入深度协作时代
人工智能·gpt
To_OC2 天前
还在追顶配模型?GPT 5.6 已经把玩法彻底改了
人工智能·gpt·llm
Days20503 天前
帮我在书本上画出了回忆中的学校-提示词
人工智能·gpt·ai作画·gpt-image
就是一顿骚操作3 天前
GPT-2 from scratch with torch:用 torch 从零实现 GPT-2
人工智能·gpt·transformer·论文解读·gpt-2
sugar__salt3 天前
Benchmark 与 GPT 5.6:大模型评测体系与 AI 工作方式的范式转移
人工智能·gpt
大鱼>3 天前
Whisper+GPT-SoVITS:语音识别到音色克隆的全链路实战
gpt·whisper·语音识别
库拉大叔4 天前
在盈彩AI使用GPT-Image-2:从入门到精通的完整指南
人工智能·gpt
吨吨ai4 天前
2026年7月更新:ChatGPT、Codex、Pro、Plus 背后的 AI Determinism 问题(GPT-5.6 工程化技术分享)
人工智能·gpt·chatgpt