File size: 2,450 Bytes
4829087
c9814b0
4829087
 
22e0523
9ebbd09
6b4a34a
 
4829087
22e0523
4829087
 
 
 
c9814b0
4829087
 
 
6b4a34a
4829087
6b4a34a
4829087
 
 
 
 
6b4a34a
b39741a
4829087
 
 
b39741a
4829087
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
6b4a34a
22e0523
 
4829087
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
# 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)))