【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()
相关推荐
向量引擎小橙8 小时前
视觉艺术的“奇点”:深度拆解 Gemini-3-Pro-Image-Preview 绘画模型,看这只“香蕉”如何重塑 AI 创作逻辑!
人工智能·python·gpt·深度学习·llama
阿乐艾官17 小时前
【MBR与GPT分区】
gpt
相思半2 天前
告别聊天机器人!2026 智能体元年:Claude 4.6 vs GPT-5.3 vs OpenClaw 全方位对比
人工智能·gpt·深度学习·claude·codex·智能体·seedance
冬奇Lab3 天前
一天一个开源项目(第22篇):nanochat - 百元级「最好的 ChatGPT」,Karpathy 的极简 LLM 训练套件
人工智能·gpt·chatgpt
赛博鲁迅3 天前
dify添加中转站模型教程
人工智能·gpt·aigc·ai编程·dify·ai-native
向量引擎小橙3 天前
从“对话助手”到“数字架构师”:Claude 4.6 Opus 如何凭一己之力,终结全球程序员的“CRUD 焦虑”?
人工智能·python·gpt·深度学习
DisonTangor3 天前
介绍 GPT‑5.3‑Codex‑Spark
大数据·gpt·spark
骇城迷影4 天前
从零复现GPT-2 124M
人工智能·pytorch·python·gpt·深度学习
赛博鲁迅4 天前
coze 工作流使用中转API 教程
gpt·大模型·ai编程·agi·gemini·coze
代码AI弗森4 天前
243 行 microGPT:把“训练 + 推理”拆到骨头里
gpt