【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()
相关推荐
Maynor9963 小时前
Codex 中国站正式上线!
人工智能·gpt·macos·github
HXR_plume4 小时前
【论文精读】生成式预训练之BART
人工智能·gpt·bert
147API7 小时前
2026 国内 GPT API 中转站测评:147AI、PoloAPI、星链4SAPI 怎么选
gpt·api中转·api大模型
DigitalOcean21 小时前
DeepSeek 推理接近 4 倍提速,这家 AI 推理云是怎么做到的?
gpt·claude·deepseek
Resistance丶未来21 小时前
GPT-5.5 深度评测:性能边界与实战价值全解析
gpt·大模型·api·claude·gemini·api key·gpt5.5
AI周红伟21 小时前
周红伟:GPT-Image-2深度解析:从技术原理到实战教程,为什么它能让整个AI圈炸锅?
人工智能·gpt·深度学习·机器学习·语言模型·openclaw
GEO索引未来1 天前
国内首部GEO可信传播标准立项通过/DeepSeek-V4 正式上线并开源/Open AI、Google继续推进AI广告标准化
大数据·人工智能·gpt·ai·chatgpt·开源
开心的AI频道1 天前
如何看待 OpenAI 近期小范围内测的 GPT-image-2 生图模型?
人工智能·gpt
皆过客,揽星河1 天前
如何在 Edge 浏览器中使用 Deepsider 插件调用 GPT-Image-2.0
gpt·ai·ai作画·硬件工程·ai提示词·gpt-image-2.0·最新gpt版本体验
码字小学妹1 天前
GPT-5.5 API 接入教程:1M 上下文 + Agent 能力登顶 Terminal-Bench
gpt