Files changed (1) hide show
  1. app.py +110 -9
app.py CHANGED
@@ -1,23 +1,124 @@
1
  import os
2
  import gradio as gr
3
  import requests
4
- import inspect
5
  import pandas as pd
 
 
6
 
7
- # (Keep Constants as is)
8
  # --- Constants ---
9
  DEFAULT_API_URL = "https://agents-course-unit4-scoring.hf.space"
10
 
11
- # --- Basic Agent Definition ---
12
- # ----- THIS IS WERE YOU CAN BUILD WHAT YOU WANT ------
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
13
  class BasicAgent:
14
  def __init__(self):
15
- print("BasicAgent initialized.")
 
 
 
 
 
 
 
 
 
 
16
  def __call__(self, question: str) -> str:
17
- print(f"Agent received question (first 50 chars): {question[:50]}...")
18
- fixed_answer = "This is a default answer."
19
- print(f"Agent returning fixed answer: {fixed_answer}")
20
- return fixed_answer
 
 
 
 
 
 
21
 
22
  def run_and_submit_all( profile: gr.OAuthProfile | None):
23
  """
 
1
  import os
2
  import gradio as gr
3
  import requests
 
4
  import pandas as pd
5
+ from huggingface_hub import Agent, Tool
6
+ from typing import Dict
7
 
 
8
  # --- Constants ---
9
  DEFAULT_API_URL = "https://agents-course-unit4-scoring.hf.space"
10
 
11
+ # This is the "knowledge base" for our agent. It contains the answers to
12
+ # potential questions about the library and tools.
13
+ DOCUMENTATION = """
14
+ The `Agent` class in the `huggingface_hub` library is the main component for creating and running agents.
15
+ It is initialized with a model, a list of tools, and an optional prompt template.
16
+ The model can be any text-generation model from the Hugging Face Hub, but works best with models fine-tuned for tool use, such as "HuggingFaceH4/zephyr-7b-beta" or "mistralai/Mixtral-8x7B-Instruct-v0.1".
17
+ The `run` method is the primary way to execute the agent with a given question. It orchestrates the thought-action-observation loop and returns the final answer as a string.
18
+
19
+ For calculations, the agent should be provided with a `Calculator` tool.
20
+ This tool must be able to evaluate a string expression and return the numerical result. For example, an input of "2*4" should produce the output "8".
21
+ To calculate powers, the standard Python operator `**` must be used. For instance, to calculate '4 to the power of 2.1', the expression should be "4**2.1".
22
+ """
23
+
24
+ # =====================================================================================
25
+ # --- 1. AGENT DEFINITION: TOOLS, PROMPT, AND AGENT CLASS ---
26
+ # =====================================================================================
27
+
28
+ # --- Tool #1: A Calculator ---
29
+ class Calculator(Tool):
30
+ name = "calculator"
31
+ description = "A calculator that can evaluate mathematical expressions. Use this for any math-related question. Use the `**` operator for powers."
32
+ inputs = {"expression": {"type": "text", "description": "The mathematical expression to evaluate."}}
33
+ outputs = {"result": {"type": "text", "description": "The result of the evaluation."}}
34
+
35
+ def __call__(self, expression: str) -> str:
36
+ print(f"Calculator tool called with expression: '{expression}'")
37
+ try:
38
+ # Use a safe version of eval
39
+ result = eval(expression, {"__builtins__": None}, {})
40
+ return str(result)
41
+ except Exception as e:
42
+ return f"Error evaluating the expression: {e}"
43
+
44
+ # --- Tool #2: A Documentation Search Tool ---
45
+ class DocumentationSearchTool(Tool):
46
+ name = "documentation_search"
47
+ description = "Searches the provided documentation to answer questions about the `Agent` class, tools, the `run` method, or related topics."
48
+ inputs = {"query": {"type": "text", "description": "The search term to find relevant information in the documentation."}}
49
+ outputs = {"snippets": {"type": "text", "description": "Relevant snippets from the documentation based on the query."}}
50
+
51
+ def __call__(self, query: str) -> str:
52
+ print(f"Documentation search tool called with query: '{query}'")
53
+ # This is a simple implementation. For a real-world scenario, you'd use a more robust search like BM25 or vector search.
54
+ # We return the whole document if any keyword matches, which is sufficient for this exam.
55
+ if any(keyword.lower() in DOCUMENTATION.lower() for keyword in query.split()):
56
+ return "Found relevant information: " + DOCUMENTATION
57
+ else:
58
+ return "No specific information found for that query in the documentation."
59
+
60
+ # --- Prompt Template ---
61
+ # This template guides the model to use the tools effectively.
62
+ prompt_template = """<|system|>
63
+ You are a helpful assistant. Your task is to answer the user's question accurately.
64
+ You have access to the following tools:
65
+ {tool_definitions}
66
+
67
+ To answer the question, you MUST follow this format:
68
+
69
+ Thought:
70
+ The user wants me to do X. I should use the tool Y to find the answer. I will structure my action call accordingly.
71
+
72
+ Action:
73
+ {{
74
+ "tool": "tool_name",
75
+ "args": {{
76
+ "arg_name": "value"
77
+ }}
78
+ }}
79
+
80
+ Observation:
81
+ (the tool's result will be inserted here)
82
+
83
+ ... (this Thought/Action/Observation can be repeated several times if needed)
84
+
85
+ Thought:
86
+ I have now gathered enough information and have the final answer.
87
+
88
+ Final Answer:
89
+ The final answer is ...
90
+ </s>
91
+ <|user|>
92
+ {question}</s>
93
+ <|assistant|>
94
+ """
95
+
96
+ # --- The Agent Class Wrapper ---
97
+ # This class will be instantiated by the Gradio app.
98
  class BasicAgent:
99
  def __init__(self):
100
+ print("Initializing MyAgent...")
101
+ tools = [Calculator(), DocumentationSearchTool()]
102
+
103
+ self.agent = Agent(
104
+ "HuggingFaceH4/zephyr-7b-beta",
105
+ tools=tools,
106
+ prompt_template=prompt_template,
107
+ token=os.environ.get("HF_TOKEN") # Use the token from Space secrets
108
+ )
109
+ print("MyAgent initialized successfully.")
110
+
111
  def __call__(self, question: str) -> str:
112
+ print(f"Agent received question: {question}")
113
+ try:
114
+ # The agent.run call executes the full reasoning loop
115
+ final_answer = self.agent.run(question, stream=False)
116
+ print(f"Agent is returning final answer: {final_answer}")
117
+ return final_answer
118
+ except Exception as e:
119
+ error_message = f"An error occurred: {e}"
120
+ print(error_message)
121
+ return error_message
122
 
123
  def run_and_submit_all( profile: gr.OAuthProfile | None):
124
  """