# app.py — last updated: Dec 2025 import os import traceback from dotenv import load_dotenv import gradio as gr from langchain_groq import ChatGroq from browser_use import Agent, Browser, BrowserConfig load_dotenv() # Create LLM once (fail fast if missing key) GROQ_API_KEY = os.getenv("GROQ_API_KEY") if not GROQ_API_KEY: raise RuntimeError("GROQ_API_KEY is required in environment") llm = ChatGroq(model="llama-3.3-70b-specdec", groq_api_key=GROQ_API_KEY) def run_agent_sync(message: str): if not message: return "الرجاء إدخال مهمة للاختبار." # create a fresh browser instance per request to avoid concurrency issues browser = Browser(config=BrowserConfig( headless=True, extra_chromium_args=["--no-sandbox", "--disable-setuid-sandbox"] )) try: # Agent.run might be sync or async depending on browser_use; adapt: result = agent_run_helper(message, llm, browser) return result except Exception as e: tb = traceback.format_exc() return f"فشل التشغيل:\n{str(e)}\n\nTraceback:\n{tb}" def agent_run_helper(task, llm_instance, browser_instance): # This helper adapts to sync/async Agent.run implementations. agent = Agent(task=task, llm=llm_instance, browser=browser_instance) run = getattr(agent, "run") # If run is coroutine function -> run with asyncio import inspect, asyncio if inspect.iscoroutinefunction(run): return asyncio.run(_run_async_agent(run)) else: res = run() return extract_result_text(res) async def _run_async_agent(run_coro): res = await run_coro() return extract_result_text(res) def extract_result_text(result_obj): # try several common result shapes if hasattr(result_obj, "final_result"): return str(result_obj.final_result()) if isinstance(result_obj, dict) and "result" in result_obj: return str(result_obj["result"]) return str(result_obj) demo = gr.Interface( fn=run_agent_sync, inputs=gr.Textbox(label="المهمة"), outputs=gr.Textbox(label="النتيجة"), title="Human Browser Agent — HF Space", description="اختبر الوكيل: اطرح سؤالاً وسيفتح الوكيل متصفحاً headless للبحث والإجابة." ) if __name__ == "__main__": demo.launch(server_name="0.0.0.0", server_port=int(os.environ.get("GRADIO_SERVER_PORT", 7860)))