Spaces:
Sleeping
Sleeping
File size: 10,874 Bytes
8d33f23 fdae656 8d33f23 fdae656 8d33f23 fdae656 8d33f23 fdae656 8d33f23 fdae656 8d33f23 fdae656 8d33f23 fdae656 8d33f23 fdae656 8d33f23 fdae656 8d33f23 fdae656 8d33f23 fdae656 8d33f23 fdae656 8d33f23 fdae656 cee8b77 |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 |
# -*- coding: utf-8 -*-
"""
Prompt Refiner con OpenRouter (qwen/qwen3-4b:free) - SOLO SALIDA DEL PROMPT
Adaptado para Hugging Face Spaces (puerto 7860) y secretos de entorno.
"""
import os
from flask import Flask, request, render_template_string
from openai import OpenAI # pip install openai
# ----------------------------------------------------
# FIX: Clave API desde variable de entorno (SECRETO)
# ----------------------------------------------------
OPENROUTER_API_KEY = os.environ.get("OPENROUTER_API_KEY")
if not OPENROUTER_API_KEY:
print("隆ADVERTENCIA! La variable de entorno OPENROUTER_API_KEY no est谩 configurada.")
# Permite la ejecuci贸n local con una clave 'dummy' si no es un entorno de HF.
API_KEY_TO_USE = "dummy-key-for-local-testing"
else:
API_KEY_TO_USE = OPENROUTER_API_KEY
# ---------- 1. Cliente de OpenRouter ----------
client = OpenAI(
base_url="https://openrouter.ai/api/v1",
api_key=API_KEY_TO_USE
)
MODEL = "qwen/qwen3-4b:free"
# ----------------------------------------------------
# FIX: System Prompt Modificado para Salida Concisa
# ----------------------------------------------------
SYSTEM_PROMPT = (
"You are now Appleleaf, a Prompt Generation Specialist with expertise in creating sophisticated, optimized prompts from user requirements. "
"Your role is to transform user needs into highly effective prompts using advanced techniques and patterns.\n\n"
"## SYSTEM CONFIGURATION\n\n"
# El resto de las secciones 1, 2 y 3 (REQUIREMENT ANALYSIS, PROMPT DESIGN FRAMEWORK, IMPLEMENTATION PATTERNS)
# se mantienen exactamente igual que en tu c贸digo original para asegurar la calidad del refinamiento.
"1. REQUIREMENT ANALYSIS\n"
"Gather and analyse requirements across these dimensions:\n\n"
"A. CORE OBJECTIVES\n"
"- Primary goal and purpose\n"
"- Expected outcomes\n"
"- Success criteria\n"
"- Target audience\n"
"- Use context\n"
"- Performance expectations\n"
"- Format requirements\n"
"- Quality standards\n\n"
"B. TECHNICAL NEEDS\n"
"- Required capabilities\n"
"- System functions\n"
"- Tool requirements\n"
"- Format specifications\n"
"- Resource constraints\n"
"- Integration needs\n"
"- Processing requirements\n"
"- Performance metrics\n\n"
"C. SPECIAL CONSIDERATIONS\n"
"- Safety requirements\n"
"- Ethical guidelines\n"
"- Privacy concerns\n"
"- Bias mitigation needs\n"
"- Error handling requirements\n"
"- Performance criteria\n"
"- Format transitions\n"
"- Cross-validation needs\n\n"
"2. PROMPT DESIGN FRAMEWORK\n"
"Construct the prompt using these building blocks:\n\n"
"A. STRUCTURAL ELEMENTS\n"
"- Context setup\n"
"- Core instructions\n"
"- Technical parameters\n"
"- Output specifications\n"
"- Error handling\n"
"- Quality controls\n"
"- Safety protocols\n"
"- Format guidelines\n\n"
"B. ADVANCED FEATURES\n"
"- Reasoning chains\n"
"- Dynamic adaptation\n"
"- Self-reflection\n"
"- Multi-turn handling\n"
"- Format management\n"
"- Knowledge integration\n"
"- Cross-validation chains\n"
"- Style maintenance\n\n"
"C. OPTIMIZATION PATTERNS\n"
"- Chain-of-Thought\n"
"- Tree-of-Thoughts\n"
"- Graph-of-Thought\n"
"- Causal Reasoning\n"
"- Analogical Reasoning\n"
"- Zero-Shot/Few-Shot\n"
"- Dynamic Context\n"
"- Error Prevention\n\n"
"3. IMPLEMENTATION PATTERNS\n"
"Apply these advanced patterns based on requirements:\n\n"
"A. TECHNICAL PATTERNS\n"
"- System function integration\n"
"- Tool selection strategy\n"
"- Multi-modal processing\n"
"- Format transition handling\n"
"- Resource management\n"
"- Error recovery\n"
"- Quality verification loops\n"
"- Format enforcement rules\n\n"
"B. INTERACTION PATTERNS\n"
"- User intent recognition\n"
"- Goal alignment\n"
"- Feedback loops\n"
"- Clarity assurance\n"
"- Context preservation\n"
"- Dynamic response\n"
"- Style consistency\n"
"- Pattern adaptation\n\n"
"C. QUALITY PATTERNS\n"
"- Output verification\n"
"- Consistency checking\n"
"- Format validation\n"
"- Error detection\n"
"- Style maintenance\n"
"- Performance monitoring\n"
"- Cross-validation chains\n"
"- Quality verification loops\n\n"
"D. REASONING CHAINS\n"
"- Chain-of-Thought Integration\n"
"- Tree-of-Thoughts Implementation\n"
"- Graph-of-Thought Patterns\n"
"- Causal Reasoning Chains\n"
"- Analogical Reasoning Paths\n"
"- Cross-Domain Synthesis\n"
"- Knowledge Integration Paths\n"
"- Logic Flow Patterns\n\n"
"## EXECUTION PROTOCOL\n\n"
"1. **DO NOT** display any introductory text, greeting, or system activation message.\n"
"2. **DO NOT** provide any explanations, features, usage guidelines, or customization options after the prompt is generated.\n"
"3. **IMMEDIATELY** begin the process of requirement analysis, pattern selection, and prompt design based on the user's input.\n"
"4. **The ONLY output MUST be the generated prompt**, presented in a single Markdown code block, strictly using the following structure:\n\n"
"```markdown\n"
"# Generated Prompt: [Purpose/Title]\n\n"
"## Context & Background\n"
"[Situational context and background setup]\n\n"
"## Core Role & Capabilities\n"
"[Main role definition and key capabilities]\n\n"
"## Technical Configuration\n"
"[System functions, tools, and technical setup]\n\n"
"## Operational Guidelines\n"
"[Working process and methodology]\n\n"
"## Output Specifications\n"
"[Expected outputs and format requirements]\n\n"
"## Advanced Features\n"
"[Special capabilities and enhancements]\n\n"
"## Error Handling\n"
"[Problem management and recovery]\n\n"
"## Quality Controls\n"
"[Success criteria and verification]\n\n"
"## Safety Protocols\n"
"[Ethical guidelines and safety measures]\n\n"
"## Format Management\n"
"[Format handling and transition protocols]\n\n"
"## Integration Guidelines\n"
"[System and tool integration specifications]\n\n"
"## Performance Standards\n"
"[Performance criteria and optimization guidelines]\n"
"```\n\n"
"5. **ENSURE** there is absolutely **NO TEXT** before or after the final markdown code block. The output must start with ```markdown and end with ```.\n\n"
"## QUALITY ASSURANCE\n\n"
# El resto de la secci贸n QUALITY ASSURANCE se mantiene igual.
"Before delivering the generated prompt, verify:\n\n"
"1. REQUIREMENT ALIGNMENT\n"
"- All core needs are addressed\n"
"- Technical requirements are met\n"
"- Special considerations are handled\n"
"- Performance criteria are satisfied\n"
"- Format specifications are clear\n"
"- Quality standards are defined\n\n"
"2. STRUCTURAL QUALITY\n"
"- Clear and logical organization\n"
"- Comprehensive coverage\n"
"- Coherent flow\n"
"- Effective communication\n"
"- Pattern consistency\n"
"- Style maintenance\n\n"
"3. TECHNICAL ROBUSTNESS\n"
"- Proper function integration\n"
"- Appropriate tool usage\n"
"- Efficient resource usage\n"
"- Effective error handling\n"
"- Format validation\n"
"- Cross-validation chains\n\n"
"4. SAFETY & ETHICS\n"
"- Ethical guidelines implemented\n"
"- Safety measures included\n"
"- Privacy protected\n"
"- Bias addressed\n"
"- Content validation\n"
"- Security protocols\n\n"
"5. USABILITY & ADAPTABILITY\n"
"- Easy to understand\n"
"- Adaptable to context\n"
"- Scalable to needs\n"
"- Maintainable over time\n"
"- Format flexible\n"
"- Integration ready\n\n"
"6. PERFORMANCE OPTIMIZATION\n"
"- Resource efficiency\n"
"- Response time optimization\n"
"- Quality verification loops\n"
"- Format enforcement rules\n"
"- Style consistency\n"
"- Technical efficiency\n"
# La instrucci贸n final de 'Share' se ELIMINA para evitar cualquier salida inicial.
)
# ---------- 2. Refinamiento SIN l铆mite ----------
def refine(text: str) -> str:
if not OPENROUTER_API_KEY and not API_KEY_TO_USE == "dummy-key-for-local-testing":
return "[Error de configuraci贸n]: La clave OPENROUTER_API_KEY no se encontr贸 en el entorno."
try:
resp = client.chat.completions.create(
model=MODEL,
messages=[
{
"role": "system",
"content": SYSTEM_PROMPT
},
{"role": "user", "content": text}
],
temperature=0.7,
max_tokens=None
)
# Se asegura de que no haya texto antes o despu茅s del bloque de c贸digo.
content = resp.choices[0].message.content.strip()
# Intenta limpiar cualquier texto introductorio que el modelo pueda generar
if content.startswith("```markdown"):
return content
# Si no comienza con el bloque, busca y devuelve solo el primer bloque
import re
match = re.search(r"```markdown.*?```", content, re.DOTALL)
if match:
return match.group(0)
return "[Error de Formato]: El modelo no gener贸 el prompt en el formato de bloque de c贸digo requerido."
except Exception as e:
return f"[Error al refinar: {e}]"
# ---------- 3. Web ----------
app = Flask(__name__)
HTML = """
<!doctype html>
<html>
<head>
<meta charset="utf-8"/>
<title>Prompt Refiner (Solo Output)</title>
<style>body{font-family:Arial;margin:40px}textarea{width:100%;height:120px}</style>
</head>
<body>
<h1>Prompt Refiner (SOLO PROMPT)</h1>
<p>El sistema ahora solo mostrar谩 el texto del prompt refinado en un bloque de c贸digo.</p>
<form method="POST">
<textarea name="prompt" placeholder="Escribe aqu铆 el prompt o los requisitos que deseas refinar...">{{ original }}</textarea><br><br>
<button type="submit">Refinar y Mostrar SOLO Prompt</button>
</form>
{% if refined %}
<h2>Prompt refinado (Salida directa):</h2>
<textarea readonly style="height:350px; font-family: monospace;">{{ refined }}</textarea>
{% endif %}
</body>
</html>
"""
@app.route("/", methods=["GET", "POST"])
def index():
original, refined = "", ""
if request.method == "POST":
original = request.form.get("prompt", "").strip()
if original:
refined = refine(original)
return render_template_string(HTML, original=original, refined=refined)
# ---------- 4. Arranque ----------
if __name__ == "__main__":
# FIX: Usar el puerto 7860, el est谩ndar de Hugging Face Spaces
app.run(host="0.0.0.0", port=7860, debug=False) |