【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()
相关推荐
卖芒果的潇洒农民12 小时前
20260201 GPT VPC中的CIDR Block 概念
笔记·gpt
薛定谔的猫198213 小时前
二十、使用PyTorch和Hugging Face Transformers训练中文GPT-2模型的技术实践
人工智能·pytorch·gpt
向量引擎小橙3 天前
Google 帝国的绝地反击:Gemini 3 深度硬核测评——GPT-5 的噩梦来了吗?
开发语言·人工智能·gpt·深度学习·机器学习
原来是你~呀~3 天前
Kali GPT - 人工智能渗透测试助手Linux部署
linux·人工智能·gpt·网络安全·自动化渗透测试
康康的AI博客3 天前
2026 OpenAI技术全景:GPT-5.2领衔的AI革命与DMXAPI无缝替代方案
人工智能·gpt
范桂飓3 天前
Transformer 大模型架构深度解析(5)GPT 与 LLM 大语言模型技术解析
人工智能·gpt·语言模型·transformer
七夜zippoe4 天前
大模型低成本高性能演进 从GPT到DeepSeek的技术实战手记
人工智能·gpt·算法·架构·deepseek
独自归家的兔4 天前
实测拆解:Qwen3-Max-Thinking 到底能不能对标 GPT-5.2?
gpt
迈火5 天前
Facerestore CF (Code Former):ComfyUI人脸修复的卓越解决方案
人工智能·gpt·计算机视觉·stable diffusion·aigc·语音识别·midjourney
百***78755 天前
Sora Video2深度解析:AI视频创作的效率革命与生态进化
java·人工智能·gpt