【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()
相关推荐
AI砖家4 小时前
DeepSeek V4.1 Flash vs. GPT-5.6 Sol:前沿闭源与高效开源,路线已经分叉
gpt·开源·deepseek
小粉粉hhh5 小时前
大模型RAG和Agent智能体(一)——初了解
gpt·langchain·aigc
kkkkkkkkkk_Z6 小时前
新手自学嵌入式 | 学习日记:EPIT/GPT定时器、输入捕获与PWM、UART通信与Modbus协议
单片机·gpt·学习
.Bryce.1 天前
你了解 Blackboard(黑板系统)吗?听说过基于黑板系统实现的智能体吗?
java·网络·gpt·php·agent·codex·黑板系统
zoutao983 天前
GPT-6 Luna 批量处理实战指南
gpt·ai写作
Web3&Basketball3 天前
决策模型vs GPT-5实测:便宜400倍
人工智能·python·gpt·大模型·ai落地·推理优化·决策模型
Jay_帅小伙4 天前
免费GPT
gpt
空堂与归4 天前
Gemini 4 Argon 发布:物理推理模型控机器人?
人工智能·gpt·ui·ai·机器人
西索斯coding5 天前
gpt-5.6-sol 接入 LobeChat 保姆级教程:endpoint 路径确认 + model 枚举填错会静默回退 gpt-5.5,收藏这篇就够了
gpt·ai