【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()
相关推荐
奇牙coding7 分钟前
GPT-5.5 报 401 invalid_api_key 怎么办?换密钥前按 4 层排查请求头、项目权限和端点
数据库·gpt·ios·ai
变量棱镜1 天前
ChatGPT 将给付费用户看广告
gpt·ai·openai
技术小甜甜1 天前
【Copilot】能选 Claude 和 GPT-6 了,Excel 分析该交给谁
gpt·excel·copilot·claude·microsoft365·gpt-6
jiangliushi62 天前
GPT-6.1 Sol 免费用:PowerShell 装 Codex 报“禁止运行脚本 npm.ps1”?一条命令解决
前端·gpt·npm
嘎嘎风3 天前
MiniMind 学习笔记之 25 Web UI 与 LLaMA-Factory:两条“不写代码”的路径
gpt·llm·源码阅读
feasibility.3 天前
具身智能的进化分水岭:GPT-6-Astra踏进能力门,却卡在实用门——商汤联合团队开源RoboRSI:Harness递归改进能否填平这道落地鸿沟?
人工智能·gpt·机器人·具身智能·vla·harness·rsi
Eloudy3 天前
全文 - Astranomy: An empirical study of GPT-6 Astra as a native robot policy
gpt
jiangliushi63 天前
GPT-6.1 Sol 免费用:pip install 太慢、超时?换清华镜像,再让 Codex 帮你写脚本
gpt·pip
jiangliushi63 天前
GPT-6.1 Sol 免费用:Windows 装完 Codex 提示“不是内部或外部命令”?三步加好 PATH
windows·gpt
TMT星球3 天前
觅蜂联合发起具身评测平台RoboColiseum,GPT-6、Opus 5.5、Gemini 4同台决战!
人工智能·gpt