【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()
相关推荐
●VON18 小时前
四大AI生图工具横评:GPT Image 2 一骑绝尘!但Gemini的免费策略才是真正的王炸
人工智能·gpt·chatgpt·大模型·image
147API20 小时前
GPT5.5 提示词迁移指南:从过程指令到任务契约
人工智能·gpt
七牛云行业应用21 小时前
Claude 4 vs GPT-5 API 对比【2026最新】:性能基准、定价与选型完整指南
gpt
多年小白1 天前
【本周复盘】2026年5月6日-5月10日(3个交易日)
人工智能·科技·gpt·深度学习·ai
陈天伟教授1 天前
图解人工智能(1)居里点
大数据·开发语言·人工智能·gpt
多年小白1 天前
【行情复盘】2026年5月8日(周五)
大数据·人工智能·科技·gpt·深度学习·ai
Android出海1 天前
ChatGPT降智怎么恢复?GPT-5.4降智原因与恢复方法
人工智能·gpt·ai·chatgpt·openai
Maynor9961 天前
MaynorAI代充现已支持 GPT Pro 代充:质保服务,可开发票
gpt
热爱生活的五柒2 天前
codex如何使用gpt模型来操控电脑软件?如何接入gmail、github等?
gpt
谙弆悕博士2 天前
GPT-5.5 Instant 免费开放背后的技术跃迁与战略阳谋
人工智能·python·gpt·chatgpt·学习方法·业界资讯