File size: 5,105 Bytes
c1533a9
 
 
bc11341
c1533a9
464ca77
 
 
 
 
 
 
66625a5
 
464ca77
 
 
66625a5
464ca77
66625a5
d821c99
4aeba84
 
 
 
 
ef1227c
c1533a9
ef1227c
 
c1533a9
ef1227c
c1533a9
d821c99
 
 
 
c1533a9
 
 
c4a1edb
 
 
 
d821c99
 
 
 
 
c1533a9
c4a1edb
 
 
c1533a9
 
ef1227c
c1533a9
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
c4a1edb
c1533a9
 
3c657c9
c1533a9
 
ef1227c
c1533a9
 
ef1227c
c1533a9
 
 
d821c99
c1533a9
ef1227c
4aeba84
36631f3
 
 
 
 
 
 
 
d821c99
 
c1533a9
 
 
 
 
 
 
 
 
 
ef1227c
c1533a9
66625a5
464ca77
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
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"""
    <div style="background-color: #2e7d32; color: white; padding: 15px; text-align: center; border-radius: 8px; font-family: sans-serif; margin-bottom: 20px;">
        <span style="font-size: 1.2em; font-weight: bold;">🌍 Your Worldwide Web App Link Is Live!</span><br>
        <span style="font-size: 0.95em;">Share this direct link with anyone in the world:</span><br>
        <a href="{worldwide_url}" target="_blank" style="color: #a3e635; font-weight: bold; text-decoration: underline; font-size: 1.1em;">{worldwide_url}</a>
    </div>
    """)

    gr.Markdown("# πŸŽ“ Ryusei: Advanced Autonomous Research Tutor (HF Engine)")
    gr.Markdown("An autonomous agent that drives a cloud browser using Hugging Face Hub models to research text layouts.")
    
    with gr.Row():
        topic_input = gr.Textbox(
            label="What concept, technology, or school topic do you want to learn about?",
            placeholder="e.g., How computer RAM stores temporary variables, or the process of cellular mitosis."
        )
    
    launch_btn = gr.Button("Start Researching", variant="primary")
    output_panel = gr.Markdown()
    
    launch_btn.click(fn=ryusei_study_session, inputs=topic_input, outputs=output_panel)

# Launch the Gradio dashboard app
demo.queue().launch(theme=gr.themes.Default())