sirine1712 commited on
Commit
4c934c3
·
verified ·
1 Parent(s): 2425e40

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +67 -44
app.py CHANGED
@@ -1,47 +1,70 @@
1
  import os
2
  import gradio as gr
3
- from langchain.agents import initialize_agent, Tool
4
- from langchain.agents.agent_types import AgentType
5
- from langchain.tools import DuckDuckGoSearchRun
6
- from langchain.llms import OpenAI
7
- from langchain.utilities import SerpAPIWrapper
8
- from langchain_core.tools import Tool
9
-
10
- # Set your API key
11
- openai_api_key = os.getenv("OPENAI_API_KEY")
12
-
13
- # Initialize the LLM
14
- llm = OpenAI(temperature=0.7, openai_api_key=openai_api_key)
15
-
16
- # Define tools the agent can use
17
- search = DuckDuckGoSearchRun()
18
-
19
- tools = [
20
- Tool(
21
- name="DuckDuckGo Search",
22
- func=search.run,
23
- description="Useful for answering questions about current events or factual information."
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
24
  )
25
- ]
26
-
27
- # Initialize the agent
28
- agent = initialize_agent(
29
- tools=tools,
30
- llm=llm,
31
- agent=AgentType.ZERO_SHOT_REACT_DESCRIPTION,
32
- verbose=True
33
- )
34
-
35
- # Gradio interface
36
- def agent_response(user_input):
37
- return agent.run(user_input)
38
-
39
- demo = gr.Interface(
40
- fn=agent_response,
41
- inputs=gr.Textbox(lines=2, placeholder="Ask me anything..."),
42
- outputs="text",
43
- title="🔍 AI Agent with Tools",
44
- description="This agent uses a language model with optional web search via DuckDuckGo to answer your queries."
45
- )
46
-
47
- demo.launch()
 
1
  import os
2
  import gradio as gr
3
+ import requests
4
+ import pandas as pd
5
+ from smolagents import Agent
6
+
7
+ DEFAULT_API_URL = "https://agents-course-unit4-scoring.hf.space"
8
+
9
+ # A simple agent using Hugging Face hosted inference API
10
+ class HuggingFaceAPIAgent(Agent):
11
+ def __init__(self, model="google/flan-t5-small"):
12
+ self.model = model
13
+ self.api_url = f"https://api-inference.huggingface.co/models/{model}"
14
+ self.headers = {"Authorization": f"Bearer {os.getenv('HF_TOKEN')}"}
15
+
16
+ def __call__(self, question: str) -> str:
17
+ print(f"Calling HF inference API for: {question[:60]}")
18
+ response = requests.post(
19
+ self.api_url,
20
+ headers=self.headers,
21
+ json={"inputs": question},
22
+ timeout=10
23
+ )
24
+ if response.status_code != 200:
25
+ print(f"API error: {response.status_code} {response.text}")
26
+ return "API call failed."
27
+ return response.json()[0]["generated_text"]
28
+
29
+ def run_and_submit_all(profile: gr.OAuthProfile | None):
30
+ if not profile:
31
+ return "Please log in first.", None
32
+
33
+ username = profile.username
34
+ agent_code = f"https://huggingface.co/spaces/{os.getenv('SPACE_ID')}/tree/main"
35
+ agent = HuggingFaceAPIAgent()
36
+
37
+ questions = requests.get(f"{DEFAULT_API_URL}/questions", timeout=15).json()
38
+ answers, log = [], []
39
+
40
+ for q in questions:
41
+ try:
42
+ answer = agent(q["question"])
43
+ except Exception as e:
44
+ answer = f"Error: {e}"
45
+ answers.append({"task_id": q["task_id"], "submitted_answer": answer})
46
+ log.append({"Task ID": q["task_id"], "Question": q["question"], "Submitted Answer": answer})
47
+
48
+ result = requests.post(f"{DEFAULT_API_URL}/submit", json={
49
+ "username": username,
50
+ "agent_code": agent_code,
51
+ "answers": answers
52
+ }).json()
53
+
54
+ message = (
55
+ f"✅ Submission complete!\n"
56
+ f"Score: {result.get('score')}%\n"
57
+ f"{result.get('correct_count')}/{result.get('total_attempted')} correct\n"
58
+ f"Message: {result.get('message')}"
59
  )
60
+ return message, pd.DataFrame(log)
61
+
62
+ with gr.Blocks() as demo:
63
+ gr.Markdown("# 🤖 SmolAgent with Hugging Face Inference API")
64
+ gr.LoginButton()
65
+ btn = gr.Button("Run Agent & Submit")
66
+ status = gr.Textbox(label="Status")
67
+ results = gr.DataFrame(label="Results")
68
+ btn.click(fn=run_and_submit_all, outputs=[status, results])
69
+
70
+ demo.launch()