Spaces:
Sleeping
Sleeping
Update agent.py
Browse files
agent.py
CHANGED
|
@@ -2,9 +2,9 @@ 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,14 +78,13 @@ def web_search(query: str) -> str:
|
|
| 78 |
except Exception as e:
|
| 79 |
return f"Search error: {e}"
|
| 80 |
|
| 81 |
-
# ---------- Custom Model
|
| 82 |
class CustomHFModel(Model):
|
| 83 |
-
def __init__(self, model_id="
|
| 84 |
super().__init__(**kwargs)
|
|
|
|
| 85 |
self.model_id = model_id
|
| 86 |
-
|
| 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,
|
|
@@ -97,77 +96,27 @@ class CustomHFModel(Model):
|
|
| 97 |
**kwargs
|
| 98 |
):
|
| 99 |
"""
|
| 100 |
-
Convert
|
| 101 |
-
Format:
|
| 102 |
-
<|system|>\n{system}<|end|>\n<|user|>\n{user}<|end|>\n<|assistant|>\n{assistant}<|end|>\n...
|
| 103 |
-
Finally add <|assistant|>\n to start generation.
|
| 104 |
"""
|
| 105 |
-
|
| 106 |
-
|
| 107 |
-
|
| 108 |
for msg in messages:
|
| 109 |
-
# Extract role and content safely
|
| 110 |
if hasattr(msg, 'role'):
|
| 111 |
-
role
|
| 112 |
-
content = msg.content
|
| 113 |
-
else:
|
| 114 |
-
role = msg['role']
|
| 115 |
-
content = msg['content']
|
| 116 |
-
|
| 117 |
-
# Ensure content is a string (if list, join it)
|
| 118 |
-
if isinstance(content, list):
|
| 119 |
-
content = " ".join(str(part) for part in content if isinstance(part, str))
|
| 120 |
else:
|
| 121 |
-
|
| 122 |
-
|
| 123 |
-
if role == "system":
|
| 124 |
-
system_content = content
|
| 125 |
-
elif role == "user":
|
| 126 |
-
# Prepend system prompt if available and this is the first user message
|
| 127 |
-
if system_content is not None:
|
| 128 |
-
content = f"{system_content}\n\n{content}"
|
| 129 |
-
system_content = None
|
| 130 |
-
prompt += f"<|user|>\n{content}<|end|>\n"
|
| 131 |
-
elif role == "assistant":
|
| 132 |
-
prompt += f"<|assistant|>\n{content}<|end|>\n"
|
| 133 |
-
else:
|
| 134 |
-
logger.warning(f"Unknown role: {role}")
|
| 135 |
-
|
| 136 |
-
# Add final assistant header to start generation
|
| 137 |
-
prompt += "<|assistant|>\n"
|
| 138 |
-
|
| 139 |
-
logger.debug(f"Final prompt (first 200 chars): {prompt[:200]}...")
|
| 140 |
-
|
| 141 |
-
payload = {
|
| 142 |
-
"inputs": prompt,
|
| 143 |
-
"parameters": {
|
| 144 |
-
"max_new_tokens": max_tokens,
|
| 145 |
-
"temperature": temperature,
|
| 146 |
-
"stop": stop_sequences or ["<|end|>"],
|
| 147 |
-
"return_full_text": False
|
| 148 |
-
}
|
| 149 |
-
}
|
| 150 |
|
| 151 |
try:
|
| 152 |
-
response =
|
| 153 |
-
|
| 154 |
-
|
| 155 |
-
|
| 156 |
-
|
| 157 |
-
|
| 158 |
-
|
| 159 |
-
|
| 160 |
-
generated = result.get("generated_text", "")
|
| 161 |
-
|
| 162 |
-
# Clean up: remove any leftover prompt if present
|
| 163 |
-
if generated.startswith(prompt):
|
| 164 |
-
generated = generated[len(prompt):]
|
| 165 |
-
return generated.strip()
|
| 166 |
except Exception as e:
|
| 167 |
-
logger.error(f"
|
| 168 |
-
if 'response' in locals() and response is not None:
|
| 169 |
-
logger.error(f"Response status: {response.status_code}")
|
| 170 |
-
logger.error(f"Response body: {response.text[:500]}")
|
| 171 |
raise Exception(f"Model {self.model_id} inference failed: {e}")
|
| 172 |
|
| 173 |
# ---------- Assemble the Agent ----------
|
|
@@ -179,7 +128,7 @@ try:
|
|
| 179 |
except ImportError:
|
| 180 |
logger.warning("⚠️ duckduckgo-search not installed, web_search disabled.")
|
| 181 |
|
| 182 |
-
model = CustomHFModel()
|
| 183 |
agent = CodeAgent(tools=tools, model=model)
|
| 184 |
|
| 185 |
# ---------- 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 Model
|
| 7 |
+
from huggingface_hub import InferenceClient
|
| 8 |
|
| 9 |
# Set up logging
|
| 10 |
logging.basicConfig(level=logging.INFO)
|
|
|
|
| 78 |
except Exception as e:
|
| 79 |
return f"Search error: {e}"
|
| 80 |
|
| 81 |
+
# ---------- Custom Model using HuggingFace InferenceClient ----------
|
| 82 |
class CustomHFModel(Model):
|
| 83 |
+
def __init__(self, model_id="mistralai/Mistral-7B-Instruct-v0.2", **kwargs):
|
| 84 |
super().__init__(**kwargs)
|
| 85 |
+
self.client = InferenceClient(model=model_id, token=hf_token)
|
| 86 |
self.model_id = model_id
|
| 87 |
+
logger.info(f"✅ CustomHFModel initialized with model: {model_id}")
|
|
|
|
|
|
|
| 88 |
|
| 89 |
def generate(
|
| 90 |
self,
|
|
|
|
| 96 |
**kwargs
|
| 97 |
):
|
| 98 |
"""
|
| 99 |
+
Convert ChatMessage objects to plain dicts and call InferenceClient.
|
|
|
|
|
|
|
|
|
|
| 100 |
"""
|
| 101 |
+
# Convert each message to a plain dictionary
|
| 102 |
+
dict_messages = []
|
|
|
|
| 103 |
for msg in messages:
|
|
|
|
| 104 |
if hasattr(msg, 'role'):
|
| 105 |
+
dict_messages.append({"role": msg.role, "content": msg.content})
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 106 |
else:
|
| 107 |
+
dict_messages.append(msg) # assume already dict
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 108 |
|
| 109 |
try:
|
| 110 |
+
response = self.client.chat_completion(
|
| 111 |
+
messages=dict_messages,
|
| 112 |
+
max_tokens=max_tokens,
|
| 113 |
+
temperature=temperature,
|
| 114 |
+
stop=stop_sequences,
|
| 115 |
+
**kwargs
|
| 116 |
+
)
|
| 117 |
+
return response.choices[0].message.content
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 118 |
except Exception as e:
|
| 119 |
+
logger.error(f"InferenceClient error: {e}")
|
|
|
|
|
|
|
|
|
|
| 120 |
raise Exception(f"Model {self.model_id} inference failed: {e}")
|
| 121 |
|
| 122 |
# ---------- Assemble the Agent ----------
|
|
|
|
| 128 |
except ImportError:
|
| 129 |
logger.warning("⚠️ duckduckgo-search not installed, web_search disabled.")
|
| 130 |
|
| 131 |
+
model = CustomHFModel() # you can change the model_id if needed
|
| 132 |
agent = CodeAgent(tools=tools, model=model)
|
| 133 |
|
| 134 |
# ---------- Class Expected by app.py ----------
|