82 lines
2.5 KiB
Python
82 lines
2.5 KiB
Python
import os
|
|
from openai import OpenAI
|
|
import json
|
|
|
|
# 初始化 OpenAI 客户端
|
|
client = OpenAI(
|
|
api_key=os.getenv("DASHSCOPE_API_KEY"),
|
|
base_url="https://dashscope.aliyuncs.com/compatible-mode/v1",
|
|
)
|
|
|
|
|
|
def delete_all_files():
|
|
"""
|
|
查询所有文件并删除。
|
|
"""
|
|
try:
|
|
# 获取文件列表
|
|
file_stk = client.files.list()
|
|
|
|
# 将文件信息解析为 JSON 格式
|
|
file_data = json.loads(file_stk.model_dump_json())
|
|
|
|
# 提取所有文件的 id
|
|
file_ids = [file["id"] for file in file_data["data"]]
|
|
|
|
# 循环删除每个文件
|
|
for file_id in file_ids:
|
|
file_object = client.files.delete(file_id)
|
|
print(f"Deleted file with id: {file_id} - {file_object.model_dump_json()}")
|
|
|
|
except Exception as e:
|
|
print(f"An error occurred while deleting files: {e}")
|
|
|
|
|
|
def read_file_ids(output_folder):
|
|
file_ids = []
|
|
file_ids_path = os.path.join(output_folder, 'file_ids.txt')
|
|
# 检查文件是否存在
|
|
if os.path.exists(file_ids_path):
|
|
try:
|
|
with open(file_ids_path, 'r', encoding='utf-8') as file:
|
|
# 按行读取文件内容
|
|
file_ids = [line.strip() for line in file.readlines()]
|
|
print(f"读取到的文件 ID 列表:{file_ids}")
|
|
except Exception as e:
|
|
print(f"读取 file_ids.txt 文件时发生错误: {e}")
|
|
else:
|
|
print(f"文件 {file_ids_path} 不存在。")
|
|
|
|
return file_ids
|
|
|
|
|
|
def delete_file_by_ids(file_ids):
|
|
"""
|
|
根据传入的 file_id 列表删除指定的文件。
|
|
|
|
:param file_ids: 一个包含文件 ID 的字符串列表
|
|
"""
|
|
if not isinstance(file_ids, list):
|
|
print("Error: file_ids should be a list.")
|
|
return
|
|
|
|
if not all(isinstance(file_id, str) for file_id in file_ids):
|
|
print("Error: Each file_id should be a string.")
|
|
return
|
|
|
|
try:
|
|
# 删除指定文件
|
|
for file_id in file_ids:
|
|
try:
|
|
# 假设 client.files.delete 会返回一个文件对象
|
|
file_object = client.files.delete(file_id)
|
|
# print(f"Deleted file with id: {file_id} - {file_object.model_dump_json()}")
|
|
except Exception as e:
|
|
# 处理删除单个文件时的异常
|
|
print(f"Failed to delete file with id {file_id}: {e}")
|
|
|
|
except Exception as e:
|
|
print(f"An error occurred while processing the file_ids: {e}")
|
|
|
|
if __name__ == '__main__':
|
|
delete_all_files() |