【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()
相关推荐
郑板桥301 小时前
一周AI热点速览(2026.03.31-04.06):GPT-6曝光、谷歌开源Gemma 4、资本狂飙与模型军备竞赛
人工智能·gpt·aigc
AIBox36513 小时前
openclaw api 配置排查与接入指南:网关启动、配置文件和模型接入全流程
javascript·人工智能·gpt
沪漂阿龙20 小时前
从感知机到GPT:一个1957年的“神经元”如何引爆2026年的AI革命?
人工智能·gpt·机器学习
Ashmcracker1 天前
Codex Desktop如何接入Azure OpenAI?AI Foundry部署GPT‑5.3‑codex 实操
人工智能·gpt·microsoft·azure
ipython_harley2 天前
【AGI】OpenAI核心贡献者翁家翌:修Infra的人,正在定义GPT-5
人工智能·gpt·ai·agi
Flying pigs~~2 天前
主流大模型介绍(GPT、Llama、ChatGLM、Qwen、deepseek)
gpt·chatgpt·llm·llama·moe·deepseek·混合专家模式
带娃的IT创业者2 天前
期中总结:从神经元到 GPT——AI 架构全景回顾(Version B)
人工智能·gpt·深度学习·神经网络·架构·nlp·transformer
ai大模型中转api测评2 天前
GPT-5.4 vs Gemini 3.1 Pro vs Qwen3.5-Omni:谁才是2026年最强的全能大模型?
人工智能·gpt
GEO索引未来2 天前
一文说清2026年GPT 卖货两种方式
人工智能·gpt·ai·chatgpt
Wild API3 天前
Claude 和 GPT 可以怎么搭?一个多模型调用示例讲清楚
人工智能·gpt