You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
 
AlphaGenerator/main.py

133 lines
3.2 KiB

import os
import json
import openai
from datetime import datetime
def load_config(config_file="config.json"):
try:
with open(config_file, 'r', encoding='utf-8') as f:
return json.load(f)
except FileNotFoundError:
print(f"创建配置文件: {config_file}")
with open(config_file, 'w', encoding='utf-8') as f:
json.dump({}, f, indent=4)
print("请在config.json中配置siliconflow的api信息")
return None
def create_prompt_file():
if not os.path.exists("prompt.txt"):
with open("prompt.txt", 'w', encoding='utf-8') as f:
f.write("")
print("已创建prompt.txt,请填入提示词后重新运行")
return False
return True
def read_prompt():
with open("prompt.txt", 'r', encoding='utf-8') as f:
prompt = f.read().strip()
if not prompt:
print("prompt.txt是空的,请填入提示词")
return None
return prompt
def create_result_folder():
if not os.path.exists("ai_result"):
os.makedirs("ai_result")
return "ai_result"
def call_siliconflow(api_key, prompt, model, base_url):
try:
client = openai.OpenAI(
api_key=api_key,
base_url=base_url
)
response = client.chat.completions.create(
model=model,
messages=[{"role": "user", "content": prompt}]
)
return response.choices[0].message.content
except openai.AuthenticationError:
print("API密钥错误")
except openai.RateLimitError:
print("调用频率限制")
except openai.APIError as e:
print(f"API错误: {e}")
except Exception as e:
print(f"其他错误: {e}")
return None
def save_result(result, folder):
timestamp = datetime.now().strftime("%Y%m%d%H%M%S")
filename = f"{timestamp}.txt"
filepath = os.path.join(folder, filename)
with open(filepath, 'w', encoding='utf-8') as f:
f.write(result)
print(f"结果保存到: {filepath}")
def get_ai_config(config):
if not config:
return None
service_name = list(config.keys())[0]
service_config = config[service_name]
required_fields = ["api_keys", "model", "base_url"]
for field in required_fields:
if field not in service_config:
print(f"缺少配置字段: {field}")
return None
return service_name, service_config
def main():
config = load_config()
if not config:
return
if not create_prompt_file():
return
prompt = read_prompt()
if not prompt:
return
config_result = get_ai_config(config)
if not config_result:
return
service_name, service_config = config_result
print(f"使用服务: {service_name}")
print(f"使用模型: {service_config['model']}")
folder = create_result_folder()
print("正在调用AI...")
result = call_siliconflow(
service_config["api_keys"],
prompt,
service_config["model"],
service_config["base_url"]
)
if result:
print(f"AI回复: {result[:200]}...")
save_result(result, folder)
else:
print("AI调用失败")
if __name__ == "__main__":
main()