Spaces:
Runtime error
Runtime error
Update app.py
Browse files1124346567989101112131617181914151617181920212223242526272829302223242526273132333435363738303132394034353637383940414243414243444546474849505152535455565758596061626364656667686970717273747545464748495051525354555657import osimport gradio as grfrom huggingface_hub import InferenceClientimport spaces # <--- Hugging Face's mandatory import for ZeroGPUimport spaces # Mandatory import for Hugging Face ZeroGPU
# Initialize the Hugging Face serverless client using Qwen Coder# Initialize the clientclient = InferenceClient("Qwen/Qwen2.5-Coder-32B-Instruct")
# This system prompt primes the AI to act as an elite, direct PHP and MariaDB coderSYSTEM_PROMPT = """You are a senior PHP and MariaDB software engineer specializing in backend game development. Your goal is to write highly optimized, clean, and modern procedural or object-oriented PHP algorithms.When writing code updates, prioritize writing functional backend logic and raw database interactions over building user interface designs. If database updates are required, prioritize writing raw console queries or standard PDO commands.Keep explanations concise, directly addressing logic, database structures, and performance optimization. Avoid generic conversational fluff."""
# We decorate our main function so Hugging Face allocates the space resource@spaces.GPU # <--- This prevents the "No @spaces.GPU function detected" error!def respond(message, chat_history): # Prepare chat format with our specialized rules# 1. The @spaces.GPU function MUST be simple and return the final string.# We set a low duration since API calls are fast, giving you higher queue priority.@spaces.GPU(duration=15)def call_inference_api(messages): response = "" # We call the completion directly without streaming to avoid ZeroGPU process/pickle bugs completion = client.chat_completion( messages, max_tokens=2048, temperature=0.2, ) return completion.choices[0].message.content
# 2. This is the UI helper function (runs on CPU, no pickle/generator issues)def generate_php_code(message, history): messages = [{"role": "system", "content": SYSTEM_PROMPT}] # Pack past messages so the chatbot remembers context for val in chat_history: if val[0]: messages.append({"role": "user", "content": val[0]}) if val[1]: messages.append({"role": "assistant", "content": val[1]}) # Reconstruct conversation history for user_msg, assistant_msg in history: if user_msg: messages.append({"role": "user", "content": user_msg}) if assistant_msg: messages.append({"role": "assistant", "content": assistant_msg}) messages.append({"role": "user", "content": message})
response = "" # Stream the code back in real-time try: for message_chunk in client.chat_completion( messages, max_tokens=2048, stream=True, temperature=0.2, # Low temperature forces more accurate, deterministic code logic ): token = message_chunk.choices[0].delta.content if token: response += token yield response # Call the GPU-allocated function safely reply = call_inference_api(messages) return reply except Exception as e: yield f"Error calling Hugging Face API: {str(e)}\nIf this persists, make sure the Hugging Face Serverless API is healthy."
# Build a simple, robust chat layoutwith gr.Blocks(theme=gr.themes.Soft()) as demo: gr.Markdown("# ๐ PHP Algorithm Specialist") gr.Markdown("Your private, high-speed assistant for writing backend game logic, MariaDB queries, and clean PHP algorithms.") chatbot = gr.Chatbot(height=550) msg = gr.Textbox( placeholder="e.g., Write a PHP function to handle custom player updates directly in the database...", label="Your Coding Task" ) clear = gr.ClearButton([msg, chatbot])
def user(user_message, history): return "", history + [[user_message, None]]
def bot(history): user_message = history[-1][0] bot_message_generator = respond(user_message, history[:-1]) history[-1][1] = "" for character in bot_message_generator: history[-1][1] = character yield history
msg.submit(user, [msg, chatbot], [msg, chatbot], queue=False).then( bot, chatbot, chatbot )
demo.queue()demo.launch() return f"Error occurred: {str(e)}\n\nIf this persists, the Serverless API may be temporarily rate-limiting requests. Please try again in a moment."
# 3. Clean Gradio interfacedemo = gr.ChatInterface( fn=generate_php_code, title="๐ PHP Algorithm Specialist", description="Your private, high-speed assistant for writing backend game logic, MariaDB queries, and clean PHP algorithms.", theme="soft")
if __name__ == "__main__": demo.queue() demo.launch()app.py+40-58