【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()
相关推荐
2501_948114245 天前
【2026架构实战】GPT-5.3与蒸汽数据融合:基于Open Claw与星链4SAPI的RAG落地指南
gpt·架构
小雨中_8 天前
3.1 GPT 系列:Generative Pre-Training(从 GPT-1 到 GPT-3)
人工智能·gpt·深度学习·机器学习·自然语言处理·gpt-3
香芋Yu8 天前
【2026大模型面试圣经】(2)主流大模型架构全景 | GPT/LLaMA/DeepSeek/Qwen深度对比
gpt·面试·架构
一个努力编程人8 天前
NLP领域————GPT算法
人工智能·gpt·自然语言处理
狮子座明仔9 天前
REDSearcher:如何用30B参数的小模型,在深度搜索上击败GPT-o3和Gemini?
人工智能·gpt·深度学习·microsoft·语言模型·自然语言处理
智算菩萨10 天前
2026年春节后,AI大模型格局彻底变了——Claude 4.6、GPT-5.2与六大国产模型全面横评
人工智能·gpt·ai编程
Learner__Q12 天前
GPT模型入门教程:从原理到实现
python·gpt
五月君_13 天前
除夕夜炸场!Qwen 3.5 正式发布:激活仅 17B,性能硬刚 GPT-5.2?
gpt
向量引擎小橙15 天前
视觉艺术的“奇点”:深度拆解 Gemini-3-Pro-Image-Preview 绘画模型,看这只“香蕉”如何重塑 AI 创作逻辑!
人工智能·python·gpt·深度学习·llama
阿乐艾官15 天前
【MBR与GPT分区】
gpt