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