File size: 10,457 Bytes
10e9b7d
043cb3a
10e9b7d
eccf8e4
3c4371f
4c42a76
808eedd
4c42a76
043cb3a
 
8dce943
e79359e
3db6293
e79359e
043cb3a
808eedd
e79359e
 
 
 
 
 
f35f3f0
e79359e
043cb3a
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
e79359e
5bb8fe1
043cb3a
 
 
 
 
 
 
808eedd
 
043cb3a
 
 
 
 
 
 
e80aab9
043cb3a
 
e79359e
 
 
043cb3a
dd84fb1
f35f3f0
043cb3a
f35f3f0
 
 
dd84fb1
f35f3f0
dd84fb1
f35f3f0
dd84fb1
f35f3f0
dd84fb1
043cb3a
dd84fb1
 
 
 
e79359e
dd84fb1
f35f3f0
 
043cb3a
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
e79359e
 
4c42a76
 
808eedd
8dce943
043cb3a
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
4c42a76
e79359e
5bb8fe1
4c42a76
 
808eedd
4c42a76
5bb8fe1
4c42a76
808eedd
 
 
4c42a76
 
 
 
eccf8e4
808eedd
 
 
8dce943
4c42a76
5bb8fe1
808eedd
 
 
31243f4
808eedd
 
 
 
e79359e
808eedd
 
 
 
 
 
 
5bb8fe1
4c42a76
808eedd
 
 
4c42a76
 
 
808eedd
 
 
4c42a76
 
 
 
 
5bb8fe1
e79359e
5bb8fe1
808eedd
 
 
 
 
 
 
7e4a06b
31243f4
808eedd
 
e79359e
4c42a76
e80aab9
 
4c42a76
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
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
import os
import re
import gradio as gr
import requests
import pandas as pd
from huggingface_hub import InferenceClient
from duckduckgo_search import DDGS
import wikipediaapi
from bs4 import BeautifulSoup
import pdfplumber

# ==== CONFIG ====
DEFAULT_API_URL = "https://agents-course-unit4-scoring.hf.space"
HF_TOKEN = os.getenv("HF_TOKEN")
GROK_API_KEY = os.getenv("GROK_API_KEY") or "xai-AyJXz3OAAMuQiOrPzPptUWTmsEyI9vywPpbV19S1nCpXXKWoKLqOoGc61RazPPui2fx4Ekb1durXccqz"

CONVERSATIONAL_MODELS = [
    "deepseek-ai/DeepSeek-LLM",
    "HuggingFaceH4/zephyr-7b-beta",
    "mistralai/Mistral-7B-Instruct-v0.2"
]

wiki_api = wikipediaapi.Wikipedia(language="en", user_agent="SmartAgent/1.0 ([email protected])")

# ==== UTILITY: Link/file detection ====
def extract_links(text):
    url_pattern = re.compile(r'(https?://[^\s\)\],]+)')
    return url_pattern.findall(text)

def download_file(url, out_dir="tmp_files"):
    os.makedirs(out_dir, exist_ok=True)
    filename = url.split("/")[-1].split("?")[0]
    local_path = os.path.join(out_dir, filename)
    try:
        r = requests.get(url, timeout=20)
        r.raise_for_status()
        with open(local_path, "wb") as f:
            f.write(r.content)
        return local_path
    except Exception:
        return None

# ==== File/Link Analyzers ====
def analyze_file(file_path):
    if file_path.endswith((".xlsx", ".xls")):
        try:
            df = pd.read_excel(file_path)
            return f"Excel summary: {df.head().to_markdown(index=False)}"
        except Exception as e:
            return f"Excel error: {e}"
    elif file_path.endswith(".csv"):
        try:
            df = pd.read_csv(file_path)
            return f"CSV summary: {df.head().to_markdown(index=False)}"
        except Exception as e:
            return f"CSV error: {e}"
    elif file_path.endswith(".pdf"):
        try:
            with pdfplumber.open(file_path) as pdf:
                first_page = pdf.pages[0].extract_text()
                return f"PDF text sample: {first_page[:1000]}"
        except Exception as e:
            return f"PDF error: {e}"
    elif file_path.endswith(".txt"):
        try:
            with open(file_path, encoding='utf-8') as f:
                txt = f.read()
            return f"TXT file sample: {txt[:1000]}"
        except Exception as e:
            return f"TXT error: {e}"
    else:
        return f"Unsupported file type: {file_path}"
    
def analyze_webpage(url):
    try:
        r = requests.get(url, timeout=15)
        soup = BeautifulSoup(r.text, "lxml")
        title = soup.title.string if soup.title else "No title"
        paragraphs = [p.get_text() for p in soup.find_all("p")]
        article_sample = "\n".join(paragraphs[:5])
        return f"Webpage Title: {title}\nContent sample:\n{article_sample[:1200]}"
    except Exception as e:
        return f"Webpage error: {e}"

# ==== SEARCH TOOLS ====
def duckduckgo_search(query):
    try:
        with DDGS() as ddgs:
            results = [r for r in ddgs.text(query, max_results=3)]
            bodies = [r.get("body", "") for r in results if r.get("body")]
            return "\n".join(bodies) if bodies else None
    except Exception:
        return None

def wikipedia_search(query):
    try:
        page = wiki_api.page(query)
        if page.exists() and page.summary:
            return page.summary
    except Exception:
        return None
    return None

def llm_conversational(query):
    last_error = None
    for model_id in CONVERSATIONAL_MODELS:
        try:
            hf_client = InferenceClient(model_id, token=HF_TOKEN)
            # Try conversational if available, else fallback to text_generation
            if hasattr(hf_client, "conversational"):
                result = hf_client.conversational(
                    messages=[{"role": "user", "content": query}],
                    max_new_tokens=384,
                )
                if isinstance(result, dict) and "generated_text" in result:
                    return result["generated_text"]
                elif hasattr(result, "generated_text"):
                    return result.generated_text
                elif isinstance(result, str):
                    return result
                else:
                    continue
            result = hf_client.text_generation(query, max_new_tokens=384)
            if isinstance(result, dict) and "generated_text" in result:
                return result["generated_text"]
            elif isinstance(result, str):
                return result
        except Exception as e:
            last_error = f"{model_id}: {e}"
    return None

def is_coding_question(text):
    # Basic heuristic: mentions code, function, "python", code blocks, etc.
    code_terms = [
        "python", "java", "c++", "code", "function", "write a", "script", "algorithm",
        "bug", "traceback", "error", "output", "compile", "debug"
    ]
    if any(term in text.lower() for term in code_terms):
        return True
    if re.search(r"```.+```", text, re.DOTALL):
        return True
    return False

def grok_completion(question, system_prompt=None):
    url = "https://api.x.ai/v1/chat/completions"
    headers = {
        "Content-Type": "application/json",
        "Authorization": f"Bearer {GROK_API_KEY}"
    }
    payload = {
        "messages": [
            {"role": "system", "content": system_prompt or "You are a helpful coding and research assistant."},
            {"role": "user", "content": question}
        ],
        "model": "grok-3-latest",
        "stream": False,
        "temperature": 0
    }
    try:
        r = requests.post(url, headers=headers, json=payload, timeout=45)
        r.raise_for_status()
        data = r.json()
        # Extract assistant's reply
        return data['choices'][0]['message']['content']
    except Exception as e:
        return None

# ==== SMART AGENT ====
class SmartAgent:
    def __init__(self):
        pass

    def __call__(self, question: str) -> str:
        # 1. Handle file/link
        links = extract_links(question)
        if links:
            results = []
            for url in links:
                if re.search(r"\.xlsx|\.xls|\.csv|\.pdf|\.txt", url):
                    local = download_file(url)
                    if local:
                        file_analysis = analyze_file(local)
                        results.append(f"File ({url}):\n{file_analysis}")
                else:
                    results.append(analyze_webpage(url))
            if results:
                return "\n\n".join(results)

        # 2. Coding or algorithmic problems? Try Grok FIRST
        if is_coding_question(question):
            grok_response = grok_completion(question)
            if grok_response:
                return f"[Grok] {grok_response}"

        # 3. DuckDuckGo for web knowledge
        result = duckduckgo_search(question)
        if result:
            return result
        # 4. Wikipedia for encyclopedic queries
        result = wikipedia_search(question)
        if result:
            return result
        # 5. Grok again for hard/reasoning/general (if not already tried)
        if not is_coding_question(question):
            grok_response = grok_completion(question)
            if grok_response:
                return f"[Grok] {grok_response}"

        # 6. Fallback to LLM conversational
        result = llm_conversational(question)
        if result:
            return result
        return "No answer could be found by available tools."

# ==== SUBMISSION LOGIC ====
def run_and_submit_all(profile: gr.OAuthProfile | None):
    space_id = os.getenv("SPACE_ID")
    if profile:
        username = profile.username
    else:
        return "Please Login to Hugging Face with the button.", None

    api_url = DEFAULT_API_URL
    questions_url = f"{api_url}/questions"
    submit_url = f"{api_url}/submit"

    agent = SmartAgent()
    agent_code = f"https://huggingface.co/spaces/{space_id}/tree/main"

    try:
        response = requests.get(questions_url, timeout=15)
        response.raise_for_status()
        questions_data = response.json()
    except Exception as e:
        return f"Error fetching questions: {e}", None

    results_log = []
    answers_payload = []

    for item in questions_data:
        task_id = item.get("task_id")
        question_text = item.get("question")
        if not task_id or not question_text:
            continue
        submitted_answer = agent(question_text)
        answers_payload.append({"task_id": task_id, "submitted_answer": submitted_answer})
        results_log.append({"Task ID": task_id, "Question": question_text, "Submitted Answer": submitted_answer})

    if not answers_payload:
        return "Agent did not produce any answers to submit.", pd.DataFrame(results_log)

    submission_data = {"username": username.strip(), "agent_code": agent_code, "answers": answers_payload}

    try:
        response = requests.post(submit_url, json=submission_data, timeout=60)
        response.raise_for_status()
        result_data = response.json()
        final_status = (
            f"Submission Successful!\n"
            f"User: {result_data.get('username')}\n"
            f"Overall Score: {result_data.get('score', 'N/A')}% "
            f"({result_data.get('correct_count', '?')}/{result_data.get('total_attempted', '?')} correct)\n"
            f"Message: {result_data.get('message', 'No message received.')}"
        )
        results_df = pd.DataFrame(results_log)
        return final_status, results_df
    except Exception as e:
        return f"Submission Failed: {e}", pd.DataFrame(results_log)

# ==== GRADIO UI ====
with gr.Blocks() as demo:
    gr.Markdown("# Smart Agent Evaluation Runner")
    gr.Markdown("""
        **Instructions:**
        1. Clone this space, define your agent logic, tools, packages, etc.
        2. Log in to Hugging Face.
        3. Click 'Run Evaluation & Submit All Answers' to fetch questions, run your agent, submit answers, and see the score.
    """)
    gr.LoginButton()
    run_button = gr.Button("Run Evaluation & Submit All Answers")
    status_output = gr.Textbox(label="Run Status / Submission Result", lines=5, interactive=False)
    results_table = gr.DataFrame(label="Questions and Agent Answers", wrap=True)

    run_button.click(fn=run_and_submit_all, outputs=[status_output, results_table])

if __name__ == "__main__":
    demo.launch(debug=True, share=False)