mohantest commited on
Commit
0c67574
·
verified ·
1 Parent(s): 65d51b8

Update agent.py

Browse files
Files changed (1) hide show
  1. agent.py +3 -99
agent.py CHANGED
@@ -2,9 +2,8 @@ import os
2
  import hashlib
3
  import json
4
  import logging
5
- import requests
6
  from smolagents import CodeAgent, tool
7
- from smolagents.models import Model
8
 
9
  # Set up logging
10
  logging.basicConfig(level=logging.INFO)
@@ -78,102 +77,6 @@ def web_search(query: str) -> str:
78
  except Exception as e:
79
  return f"Search error: {e}"
80
 
81
- # ---------- Custom Model with Direct HTTP (Llama-3-8B-Instruct) ----------
82
- class CustomHFModel(Model):
83
- def __init__(self, model_id="meta-llama/Meta-Llama-3-8B-Instruct", **kwargs):
84
- super().__init__(**kwargs)
85
- self.model_id = model_id
86
- self.api_url = f"https://api-inference.huggingface.co/models/{model_id}"
87
- self.headers = {"Authorization": f"Bearer {hf_token}"}
88
- logger.info(f"✅ CustomHFModel initialized with model: {model_id} (direct HTTP)")
89
-
90
- def generate(
91
- self,
92
- messages,
93
- stop_sequences=None,
94
- grammar=None,
95
- max_tokens=500,
96
- temperature=0.7,
97
- **kwargs
98
- ):
99
- """
100
- Convert messages to a prompt for Llama-3 Instruct.
101
- Format:
102
- <|begin_of_text|><|start_header_id|>system<|end_header_id|>
103
-
104
- {system}<|eot_id|><|start_header_id|>user<|end_header_id|>
105
-
106
- {user}<|eot_id|><|start_header_id|>assistant<|end_header_id|>
107
-
108
- """
109
- prompt = "<|begin_of_text|>"
110
- system_content = None
111
-
112
- for msg in messages:
113
- # Extract role and content safely
114
- if hasattr(msg, 'role'):
115
- role = msg.role
116
- content = msg.content
117
- else:
118
- role = msg['role']
119
- content = msg['content']
120
-
121
- # Ensure content is a string (if list, join it)
122
- if isinstance(content, list):
123
- content = " ".join(str(part) for part in content if isinstance(part, str))
124
- else:
125
- content = str(content)
126
-
127
- if role == "system":
128
- system_content = content
129
- elif role == "user":
130
- if system_content is not None:
131
- # Prepend system to first user message
132
- content = f"{system_content}\n\n{content}"
133
- system_content = None # use only once
134
- prompt += f"<|start_header_id|>user<|end_header_id|>\n\n{content}<|eot_id|>"
135
- elif role == "assistant":
136
- prompt += f"<|start_header_id|>assistant<|end_header_id|>\n\n{content}<|eot_id|>"
137
- else:
138
- logger.warning(f"Unknown role: {role}")
139
-
140
- # Add final assistant header to start generation
141
- prompt += "<|start_header_id|>assistant<|end_header_id|>\n\n"
142
-
143
- logger.debug(f"Final prompt (first 200 chars): {prompt[:200]}...")
144
-
145
- payload = {
146
- "inputs": prompt,
147
- "parameters": {
148
- "max_new_tokens": max_tokens,
149
- "temperature": temperature,
150
- "stop": stop_sequences or ["<|eot_id|>"],
151
- "return_full_text": False
152
- }
153
- }
154
-
155
- try:
156
- response = requests.post(self.api_url, headers=self.headers, json=payload, timeout=60)
157
- response.raise_for_status()
158
- result = response.json()
159
-
160
- # Handle API response (can be list of dicts or a single dict)
161
- if isinstance(result, list):
162
- generated = result[0].get("generated_text", "")
163
- else:
164
- generated = result.get("generated_text", "")
165
-
166
- # Clean up: remove any leftover prompt if present
167
- if generated.startswith(prompt):
168
- generated = generated[len(prompt):]
169
- return generated.strip()
170
- except Exception as e:
171
- logger.error(f"Direct HTTP inference error: {e}")
172
- if 'response' in locals() and response is not None:
173
- logger.error(f"Response status: {response.status_code}")
174
- logger.error(f"Response body: {response.text[:500]}")
175
- raise Exception(f"Model {self.model_id} inference failed: {e}")
176
-
177
  # ---------- Assemble the Agent ----------
178
  tools = [calculator]
179
  try:
@@ -183,7 +86,8 @@ try:
183
  except ImportError:
184
  logger.warning("⚠️ duckduckgo-search not installed, web_search disabled.")
185
 
186
- model = CustomHFModel()
 
187
  agent = CodeAgent(tools=tools, model=model)
188
 
189
  # ---------- Class Expected by app.py ----------
 
2
  import hashlib
3
  import json
4
  import logging
 
5
  from smolagents import CodeAgent, tool
6
+ from smolagents.models import HfApiModel # correct import
7
 
8
  # Set up logging
9
  logging.basicConfig(level=logging.INFO)
 
77
  except Exception as e:
78
  return f"Search error: {e}"
79
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
80
  # ---------- Assemble the Agent ----------
81
  tools = [calculator]
82
  try:
 
86
  except ImportError:
87
  logger.warning("⚠️ duckduckgo-search not installed, web_search disabled.")
88
 
89
+ # Use HfApiModel – it automatically selects a working endpoint
90
+ model = HfApiModel(model_id="HuggingFaceH4/zephyr-7b-beta", token=hf_token)
91
  agent = CodeAgent(tools=tools, model=model)
92
 
93
  # ---------- Class Expected by app.py ----------