Python 接入gpt

import requests
import os
from datetime import datetime
import sys

# 替换成您的API密钥
api_key = "api_key"

#代理网络,需要打开vpn
os.environ["HTTP_PROXY"] = "http://127.0.0.1:7890"
os.environ["HTTPS_PROXY"] = "http://127.0.0.1:7890"

sys.stdout.reconfigure(encoding='utf-8')

# 提问给ChatGPT
def ask_chatgpt(prompt):
    url = "https://api.openai.com/v1/chat/completions"
    headers = {
        "Authorization": f"Bearer {api_key}"
    }
    data = {
        "messages": [{"role": "user", "content": prompt}],
        "model": "gpt-3.5-turbo"
    }

    response = requests.post(url, headers=headers, json=data,timeout=60)
    response_data = response.json()
    
    return response_data

#写入内容
def write_to_file(file_name, content):
    try:
        # 打开文件,使用 'a' 模式以追加内容的方式写入
        with open(file_name, "a", encoding="utf-8") as file:
            # 写入内容
            file.write(content)
    except Exception as e:
        print("写入文件时发生错误:", e)


#获取所有txt文件
def get_txt_files(folder_path):
    """
    获取指定文件夹下的所有 .txt 文件路径
    :param folder_path: 要遍历的文件夹路径
    :return: 包含 .txt 文件路径的列表
    """
    txt_files = []
    for root, dirs, files in os.walk(folder_path):
        for file in files:
            if file.endswith('.txt'):
                txt_files.append(os.path.join(root, file))
    return txt_files

def setChatgpt(user_input):
     # 将问题添加到列表中
    questions.append("user:" + user_input)
    # 将问题写入文件
    write_to_file(chat_history_file_path,questions[-1] + "\n")
    user_input = " ".join(questions)
    try:
        response = ask_chatgpt(user_input)
        if response and response.get("choices"):
            answer = response["choices"][0]["message"]["content"]
            questions.append("chatgpt:" + answer)
            # 将回复写入文件
            write_to_file(chat_history_file_path,questions[-1] + "\n")
            # 将回复拆分成多行,以逐句呈现
            sentences = answer.split(". ")
            for sentence in sentences:
                print(f"{sentence}")

        else:
            print("未能获取有效的回复,请等待一会再输入问题")
            print("回答结束,已提出程序")
    except requests.Timeout:
        print("请求超时,请重新输入")
        print("回答结束,已提出程序")

    print("回答结束,已提出程序")


if __name__ == '__main__':
    # if len(sys.argv) != 2 | len(sys.argv) != 3:
    #     print("用法:python 脚本名.py  <问题> || 用法:python 脚本名.py <问题> <txt名字> ")
    #     sys.exit(1)

    # user_input = sys.argv[1]
    file_name = ""
    if len(sys.argv) == 3:
        file_name = sys.argv[2]

    # 修改为你要遍历的文件夹路径
    folder_path = r'E:\Dome\xxx'
    # 初始化问题列表
    questions = []
    lines = []

    # 获取当前时间
    current_time = datetime.now()
    # 使用当前时间创建一个唯一的文件名
    file_name = current_time.strftime("%Y-%m-%d") + "_chatgpt.txt" if len(file_name) == 0 else sys.argv[2]
    #合并目标文件夹路径和文件名
    chat_history_file_path = os.path.join(folder_path, file_name)

    try:
        with open(chat_history_file_path, 'r', encoding='utf-8') as file:
            for line in file:
                questions.append(line.strip())
    except FileNotFoundError:
        # 如果文件不存在,创建一个空文件
        open(chat_history_file_path, 'w', encoding='utf-8').close()

    while True:
        user_input = input("请输入问题(q退出): ")
        if user_input == "q":
            break
        elif user_input == "w":
            questions = []
            questions.append("user:你好")
        else:
            # 将问题添加到列表中
            questions.append("user:" + user_input)
        
         # 将问题写入文件
        write_to_file(chat_history_file_path,questions[-1] + "\n")
        user_input = " ".join(questions)
        try:
            response = ask_chatgpt(user_input)
            if response and response.get("choices"):
                answer = response["choices"][0]["message"]["content"]
                questions.append("chatgpt:" + answer)
                # 将回复写入文件
                write_to_file(chat_history_file_path,questions[-1] + "\n")
                # 将回复拆分成多行,以逐句呈现
                sentences = answer.split(". ")
                for sentence in sentences:
                    print(f"{sentence}")

            else:
                print("未能获取有效的回复,请等待一会再输入问题")
        except requests.Timeout:
            print("请求超时,请重新输入")

    print("回答结束,已提出程序")


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值