ai_agent / app.py
ryusei7's picture
Update app.py
c4a1edb verified
Raw
History Blame Contribute Delete
5.11 kB
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())