写一首古诗并保存
写一首古诗看看
写一首古诗

import os
import json
import requests
from datetime import datetime

# ========================================================
# 1. 定位 knowledge 目录及 key.txt 路径
# ========================================================
base_dir = os.path.dirname(os.path.abspath(__file__)) if "__file__" in globals() else os.getcwd()
knowledge_dir = os.path.join(base_dir, "knowledge") if not os.path.basename(base_dir).lower() == "knowledge" else base_dir
key_file = os.path.join(knowledge_dir, "key.txt")

# ========================================================
# 2. 动态读取 key.txt（沿用 28.txt 逻辑）
# ========================================================
if not os.path.isfile(key_file):
    result = f"执行失败：找不到 Key 配置文件：{key_file}"
else:
    with open(key_file, "r", encoding="utf-8", errors="ignore") as f:
        key_lines = [line.strip() for line in f.read().splitlines() if line.strip()]

    if not key_lines:
        result = "执行失败：knowledge/key.txt 内容为空"
    else:
        # 提取 API Key
        api_key = key_lines[0]
        if api_key.lower().startswith("api_key="):
            api_key = api_key.split("=", 1)[1].strip()

        # 提取 API URL
        api_url = "https://api.openai.com/v1/chat/completions"
        for line in key_lines[1:]:
            if line.startswith("http://") or line.startswith("https://"):
                url = line.rstrip("/")
                if url.endswith("/v1/chat/completions"):
                    api_url = url
                elif url.endswith("/v1"):
                    api_url = url + "/chat/completions"
                else:
                    api_url = url + "/v1/chat/completions"
                break

        # 提取模型名称
        model_name = "gemini-3.8-flash"
        for line in key_lines[1:]:
            if line.lower().startswith("model="):
                model_name = line.split("=", 1)[1].strip()
                break

        # ========================================================
        # 3. 构造精准提示词（严格限定只输出标题与诗句）
        # ========================================================
        sys_prompt = "你是一位古典诗人。用户输入主题后，你只输出标题和诗句本身。绝对不能输出任何解释、白话文赏析、作者、寒暄或Markdown标记。"
        user_prompt = f"请以“{query}”为主题写一首五言律诗。格式必须是：第一行为《诗题》，后面紧接着诗句，不要任何其他文字。"

        headers = {
            "Content-Type": "application/json",
            "Authorization": f"Bearer {api_key}",
        }

        payload = {
            "model": model_name,
            "messages": [
                {"role": "system", "content": sys_prompt},
                {"role": "user", "content": user_prompt},
            ],
            "temperature": 0.5,
        }

        try:
            print("开始调用接口...")
            resp = requests.post(api_url, headers=headers, json=payload, timeout=60)
            resp.raise_for_status()
            data = resp.json()
            
            # 直接提取文本，不做多余局部变量循环
            poem = data["choices"][0]["message"]["content"].strip()
            poem = poem.replace("```", "").replace("**", "").strip()

        except Exception as e:
            result = f"调用接口失败：{e}"
        else:
            # ========================================================
            # 4. 保存到桌面并返回结果
            # ========================================================
            desktop_dir = os.path.join(os.path.expanduser("~"), "Desktop")
            if not os.path.exists(desktop_dir):
                desktop_dir = r"C:\Users\lotoclize\Desktop"
            os.makedirs(desktop_dir, exist_ok=True)

            filename = datetime.now().strftime("poem_%Y%m%d_%H%M%S.txt")
            file_path = os.path.join(desktop_dir, filename)

            with open(file_path, "w", encoding="utf-8") as f:
                f.write(poem)

            result = poem
