import os import asyncio import gradio as gr from browser_use import Agent # NATIVE HUGGING FACE URL RESOLVER try: from huggingface_hub import get_space_runtime runtime = get_space_runtime(os.environ.get("SPACE_ID", "")) worldwide_url = f"https://huggingface.co/spaces/{os.environ.get('SPACE_ID', '')}" except Exception: space_id = os.environ.get("SPACE_ID", "username/space-name") try: username, space_name = space_id.split("/") clean_user = username.lower().replace("_", "-") clean_space = space_name.lower().replace("_", "-") worldwide_url = f"https://{clean_user}-{clean_space}.hf.space" except ValueError: worldwide_url = "https://huggingface.co/spaces" # Print the link directly into your Hugging Face terminal logs on startup print("\n" + "="*60) print(f"🚀 WORLDWIDE PUBLIC URL AVAILABLE AT:") print(f"🔗 {worldwide_url}") print("="*60 + "\n") async def ryusei_study_session(topic): if not topic.strip(): yield "⚠️ Please enter a topic you want to learn!" return yield f"🔄 Ryusei is launching an advanced browser session to study '{topic}'..." # Securely fetch your Hugging Face API Token from your Space settings hf_token = os.environ.get("HF_TOKEN") if not hf_token: yield "❌ Error: HF_TOKEN secret is missing in Space Settings. Please add your token under Secrets." return try: # Load the base serverless endpoint along with the Chat Wrapper wrapper from langchain_huggingface import HuggingFaceEndpoint, ChatHuggingFace base_llm = HuggingFaceEndpoint( repo_id="Qwen/Qwen2.5-7B-Instruct", task="text-generation", max_new_tokens=1500, temperature=0.1, huggingfacehub_api_token=hf_token ) # FIX: Wrap the endpoint in ChatHuggingFace so it populates 'model_name' for browser-use llm = ChatHuggingFace(llm=base_llm) study_prompt = f""" You are an elite academic tutor agent. The student wants to study and learn about: "{topic}". Execute these precise structural tasks: 1. Go to a search engine (like DuckDuckGo) and search for information on "{topic}". 2. Visit at least two separate relevant resource web links or encyclopedia entries. 3. Read the contents, filter out promotional clutter, and synthesize the educational points. 4. Output a clear, structured learning guide based on your findings. Your final response must be formatted in clean Markdown with these sections: # 📚 Master Lesson: {topic} ### 💡 Simple Analogy *(Explain the concept like I am a complete beginner using a relatable comparison)* ### 🔍 Core Principles Breakdown *(Provide clear bullet points explaining the most crucial functional components)* ### 🛠️ Practical Application *(Give a real-world example of how this topic applies or works in active industries)* """ # Let the agent auto-initialize its own hidden browser internally using the wrapped chat llm agent = Agent( task=study_prompt, llm=llm ) # Run the automated browser routine in the cloud space environment history = await agent.run() # Yield the final compiled structured study guide yield history.final_result() except Exception as e: yield f"⚠️ Studio Agent ran into an execution error: {str(e)}\n\nMake sure your HF_TOKEN is valid and your Space has internet access enabled." # Set up the visual Gradio Web Dashboard interface with gr.Blocks() as demo: gr.HTML(f"""