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 |
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,30 +78,73 @@ 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="HuggingFaceH4/zephyr-7b-beta", **kwargs):
|
| 84 |
super().__init__(**kwargs)
|
| 85 |
-
self.client = InferenceClient(model=model_id, token=hf_token)
|
| 86 |
self.model_id = model_id
|
| 87 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 88 |
|
| 89 |
-
def generate(self, messages, stop_sequences=None, grammar=None, max_tokens=500, temperature=0.7, **kwargs):
|
| 90 |
try:
|
| 91 |
-
|
| 92 |
-
|
| 93 |
-
|
| 94 |
-
|
| 95 |
-
|
| 96 |
-
|
| 97 |
-
|
| 98 |
-
|
| 99 |
-
|
| 100 |
-
|
| 101 |
-
|
|
|
|
|
|
|
|
|
|
| 102 |
except Exception as e:
|
| 103 |
-
|
| 104 |
-
|
|
|
|
|
|
|
| 105 |
raise Exception(f"Model {self.model_id} inference failed: {e}")
|
| 106 |
|
| 107 |
# ---------- Assemble the Agent ----------
|
|
|
|
| 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 |
except Exception as e:
|
| 79 |
return f"Search error: {e}"
|
| 80 |
|
| 81 |
+
# ---------- Custom Model with Direct HTTP ----------
|
| 82 |
class CustomHFModel(Model):
|
| 83 |
def __init__(self, model_id="HuggingFaceH4/zephyr-7b-beta", **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 and call the Hugging Face Inference API via HTTP.
|
| 101 |
+
"""
|
| 102 |
+
# Convert any non-dict messages to plain dicts (safety)
|
| 103 |
+
messages = [dict(msg) for msg in messages]
|
| 104 |
+
|
| 105 |
+
# Build prompt in Zephyr's chat format
|
| 106 |
+
prompt = ""
|
| 107 |
+
for msg in messages:
|
| 108 |
+
role = msg["role"]
|
| 109 |
+
content = msg["content"]
|
| 110 |
+
if role == "system":
|
| 111 |
+
prompt += f"<|system|>\n{content}\n</s>\n"
|
| 112 |
+
elif role == "user":
|
| 113 |
+
prompt += f"<|user|>\n{content}\n</s>\n"
|
| 114 |
+
elif role == "assistant":
|
| 115 |
+
prompt += f"<|assistant|>\n{content}\n</s>\n"
|
| 116 |
+
prompt += "<|assistant|>\n" # start assistant response
|
| 117 |
+
|
| 118 |
+
payload = {
|
| 119 |
+
"inputs": prompt,
|
| 120 |
+
"parameters": {
|
| 121 |
+
"max_new_tokens": max_tokens,
|
| 122 |
+
"temperature": temperature,
|
| 123 |
+
"stop": stop_sequences or [],
|
| 124 |
+
"return_full_text": False # Do not include prompt in output
|
| 125 |
+
}
|
| 126 |
+
}
|
| 127 |
|
|
|
|
| 128 |
try:
|
| 129 |
+
response = requests.post(self.api_url, headers=self.headers, json=payload, timeout=60)
|
| 130 |
+
response.raise_for_status()
|
| 131 |
+
result = response.json()
|
| 132 |
+
|
| 133 |
+
# The API returns a list of generated texts
|
| 134 |
+
if isinstance(result, list) and len(result) > 0:
|
| 135 |
+
generated = result[0].get("generated_text", "")
|
| 136 |
+
else:
|
| 137 |
+
generated = result.get("generated_text", "")
|
| 138 |
+
|
| 139 |
+
# Sometimes the prompt is still included; strip it if present
|
| 140 |
+
if generated.startswith(prompt):
|
| 141 |
+
generated = generated[len(prompt):]
|
| 142 |
+
return generated.strip()
|
| 143 |
except Exception as e:
|
| 144 |
+
logger.error(f"Direct HTTP inference error: {e}")
|
| 145 |
+
if 'response' in locals() and response is not None:
|
| 146 |
+
logger.error(f"Response status: {response.status_code}")
|
| 147 |
+
logger.error(f"Response body: {response.text[:500]}")
|
| 148 |
raise Exception(f"Model {self.model_id} inference failed: {e}")
|
| 149 |
|
| 150 |
# ---------- Assemble the Agent ----------
|