mohantest commited on
Commit
e53cc76
Β·
verified Β·
1 Parent(s): f6c3f4b

Update agent.py

Browse files
Files changed (1) hide show
  1. agent.py +28 -22
agent.py CHANGED
@@ -6,17 +6,19 @@ from smolagents import CodeAgent, tool
6
  from smolagents.models import Model
7
  from huggingface_hub import InferenceClient
8
 
 
9
  logging.basicConfig(level=logging.INFO)
10
  logger = logging.getLogger(__name__)
11
 
12
- # Check HF_TOKEN at startup
13
  hf_token = os.getenv("HF_TOKEN")
14
  if hf_token:
15
- logger.info("HF_TOKEN is set (first 4 chars: %s...)", hf_token[:4])
16
  else:
17
- logger.warning("HF_TOKEN is NOT set - inference may fail")
 
18
 
19
- # Cache for answers
20
  CACHE_FILE = "answer_cache.json"
21
  if os.path.exists(CACHE_FILE):
22
  with open(CACHE_FILE) as f:
@@ -44,6 +46,7 @@ def calculator(expression: str) -> str:
44
  if not all(c in allowed_chars for c in expression):
45
  return "Error: Expression contains disallowed characters."
46
  try:
 
47
  result = eval(expression, {"__builtins__": {}}, {})
48
  return str(result)
49
  except Exception as e:
@@ -76,18 +79,14 @@ def web_search(query: str) -> str:
76
  except Exception as e:
77
  return f"Search error: {e}"
78
 
79
- # ---------- Custom model with explicit Hugging Face endpoint ----------
80
  class CustomHFModel(Model):
81
  def __init__(self, model_id="mistralai/Mistral-7B-Instruct-v0.2", **kwargs):
82
  super().__init__(**kwargs)
83
- # Force Hugging Face inference endpoint
84
- self.client = InferenceClient(
85
- model=model_id,
86
- token=os.getenv("HF_TOKEN"),
87
- base_url="https://api-inference.huggingface.co" # Explicit HF URL
88
- )
89
  self.model_id = model_id
90
- logger.info(f"CustomHFModel initialized with model: {model_id}")
91
 
92
  def generate(
93
  self,
@@ -98,12 +97,17 @@ class CustomHFModel(Model):
98
  temperature=0.7,
99
  **kwargs
100
  ):
 
 
 
 
 
101
  try:
102
  response = self.client.chat_completion(
103
  messages=messages,
104
  max_tokens=max_tokens,
105
  temperature=temperature,
106
- stop=stop_sequences,
107
  **kwargs
108
  )
109
  return response.choices[0].message.content
@@ -111,34 +115,36 @@ class CustomHFModel(Model):
111
  # Wrap error with model info for debugging
112
  raise Exception(f"Model {self.model_id} inference failed: {e}")
113
 
114
- # ---------- Assemble the agent ----------
115
  tools = [calculator]
116
  try:
117
  import duckduckgo_search
118
  tools.append(web_search)
119
- logger.info("Web search tool enabled.")
120
  except ImportError:
121
- logger.warning("duckduckgo-search not installed, web_search disabled.")
122
 
123
- model = CustomHFModel() # You can change model_id here if needed
 
124
  agent = CodeAgent(tools=tools, model=model)
125
 
126
- # ---------- The class expected by app.py ----------
127
  class CustomAgent:
128
  def __call__(self, question: str) -> str:
129
- """Called for each question."""
130
  q_hash = hashlib.md5(question.encode()).hexdigest()
131
  if q_hash in answer_cache:
132
- logger.info(f"Cache hit for question: {question[:50]}...")
133
  return answer_cache[q_hash]
134
 
135
- logger.info(f"Processing question: {question[:50]}...")
136
  try:
137
  answer = agent.run(question)
138
  except Exception as e:
139
- logger.error(f"Agent error: {e}")
140
  answer = f"Error: {e}"
141
 
 
142
  answer_cache[q_hash] = answer
143
  save_cache()
144
  return answer
 
6
  from smolagents.models import Model
7
  from huggingface_hub import InferenceClient
8
 
9
+ # Set up logging
10
  logging.basicConfig(level=logging.INFO)
11
  logger = logging.getLogger(__name__)
12
 
13
+ # ---------- Validate Hugging Face Token ----------
14
  hf_token = os.getenv("HF_TOKEN")
15
  if hf_token:
16
+ logger.info(f"βœ… HF_TOKEN is set (first 4 chars: {hf_token[:4]}...)")
17
  else:
18
+ logger.error("❌ HF_TOKEN environment variable is NOT set. Please add it in Space secrets.")
19
+ raise ValueError("HF_TOKEN is required for inference. Stopping startup.")
20
 
21
+ # ---------- Answer Cache (persists between runs) ----------
22
  CACHE_FILE = "answer_cache.json"
23
  if os.path.exists(CACHE_FILE):
24
  with open(CACHE_FILE) as f:
 
46
  if not all(c in allowed_chars for c in expression):
47
  return "Error: Expression contains disallowed characters."
48
  try:
49
+ # Restricted eval – only numbers and basic operators allowed
50
  result = eval(expression, {"__builtins__": {}}, {})
51
  return str(result)
52
  except Exception as e:
 
79
  except Exception as e:
80
  return f"Search error: {e}"
81
 
82
+ # ---------- Custom Model (inherits from smolagents.Model) ----------
83
  class CustomHFModel(Model):
84
  def __init__(self, model_id="mistralai/Mistral-7B-Instruct-v0.2", **kwargs):
85
  super().__init__(**kwargs)
86
+ # Use only model and token – no base_url needed for Hugging Face Inference API
87
+ self.client = InferenceClient(model=model_id, token=hf_token)
 
 
 
 
88
  self.model_id = model_id
89
+ logger.info(f"βœ… CustomHFModel initialized with model: {model_id}")
90
 
91
  def generate(
92
  self,
 
97
  temperature=0.7,
98
  **kwargs
99
  ):
100
+ """
101
+ Required method for smolagents models.
102
+ Takes a list of messages (e.g., [{"role": "user", "content": "..."}])
103
+ and returns the assistant's reply as a string.
104
+ """
105
  try:
106
  response = self.client.chat_completion(
107
  messages=messages,
108
  max_tokens=max_tokens,
109
  temperature=temperature,
110
+ stop=stop_sequences, # smolagents passes stop_sequences, map to 'stop'
111
  **kwargs
112
  )
113
  return response.choices[0].message.content
 
115
  # Wrap error with model info for debugging
116
  raise Exception(f"Model {self.model_id} inference failed: {e}")
117
 
118
+ # ---------- Assemble the Agent ----------
119
  tools = [calculator]
120
  try:
121
  import duckduckgo_search
122
  tools.append(web_search)
123
+ logger.info("βœ… Web search tool enabled.")
124
  except ImportError:
125
+ logger.warning("⚠️ duckduckgo-search not installed, web_search disabled.")
126
 
127
+ # Instantiate the custom model and agent
128
+ model = CustomHFModel() # you can change the model_id if desired
129
  agent = CodeAgent(tools=tools, model=model)
130
 
131
+ # ---------- Class Expected by app.py ----------
132
  class CustomAgent:
133
  def __call__(self, question: str) -> str:
134
+ """Called by the evaluator for each question."""
135
  q_hash = hashlib.md5(question.encode()).hexdigest()
136
  if q_hash in answer_cache:
137
+ logger.info(f"πŸ“¦ Cache hit for question: {question[:50]}...")
138
  return answer_cache[q_hash]
139
 
140
+ logger.info(f"πŸ€– Processing question: {question[:50]}...")
141
  try:
142
  answer = agent.run(question)
143
  except Exception as e:
144
+ logger.error(f"❌ Agent error: {e}")
145
  answer = f"Error: {e}"
146
 
147
+ # Cache the answer for future runs
148
  answer_cache[q_hash] = answer
149
  save_cache()
150
  return answer