Spaces:
Sleeping
Sleeping
Update agent.py
Browse files
agent.py
CHANGED
|
@@ -4,19 +4,19 @@ import json
|
|
| 4 |
import logging
|
| 5 |
from smolagents import CodeAgent, tool
|
| 6 |
from smolagents.models import Model
|
| 7 |
-
|
| 8 |
|
| 9 |
# Set up logging
|
| 10 |
logging.basicConfig(level=logging.INFO)
|
| 11 |
logger = logging.getLogger(__name__)
|
| 12 |
|
| 13 |
-
# ---------- Validate
|
| 14 |
-
|
| 15 |
-
if
|
| 16 |
-
logger.info(f"β
|
| 17 |
else:
|
| 18 |
-
logger.error("β
|
| 19 |
-
raise ValueError("
|
| 20 |
|
| 21 |
# ---------- Answer Cache ----------
|
| 22 |
CACHE_FILE = "answer_cache.json"
|
|
@@ -78,13 +78,13 @@ def web_search(query: str) -> str:
|
|
| 78 |
except Exception as e:
|
| 79 |
return f"Search error: {e}"
|
| 80 |
|
| 81 |
-
# ---------- Custom Model using
|
| 82 |
-
class
|
| 83 |
-
def __init__(self,
|
| 84 |
super().__init__(**kwargs)
|
| 85 |
-
self.client =
|
| 86 |
-
self.
|
| 87 |
-
logger.info(f"β
|
| 88 |
|
| 89 |
def generate(
|
| 90 |
self,
|
|
@@ -95,49 +95,36 @@ class CustomHFModel(Model):
|
|
| 95 |
temperature=0.7,
|
| 96 |
**kwargs
|
| 97 |
):
|
| 98 |
-
#
|
| 99 |
-
|
| 100 |
-
for i, msg in enumerate(messages[:3]): # log first 3 messages
|
| 101 |
-
logger.info(f"Message {i}: type={type(msg).__name__}, repr={repr(msg)[:200]}")
|
| 102 |
-
|
| 103 |
-
# Convert every message to a dictionary safe for InferenceClient
|
| 104 |
-
dict_messages = []
|
| 105 |
for msg in messages:
|
| 106 |
if isinstance(msg, str):
|
| 107 |
-
|
| 108 |
-
dict_messages.append({"role": "user", "content": msg})
|
| 109 |
elif isinstance(msg, dict):
|
| 110 |
-
#
|
| 111 |
-
|
| 112 |
-
|
| 113 |
-
|
| 114 |
-
logger.warning(f"Dict missing role/content: {msg}")
|
| 115 |
-
# Fallback: use as user content
|
| 116 |
-
dict_messages.append({"role": "user", "content": str(msg)})
|
| 117 |
elif hasattr(msg, 'role') and hasattr(msg, 'content'):
|
| 118 |
-
|
| 119 |
-
dict_messages.append({"role": msg.role, "content": msg.content})
|
| 120 |
else:
|
| 121 |
-
# Unknown type β convert to string and use as user
|
| 122 |
logger.warning(f"Unknown message type {type(msg)} β converting to string")
|
| 123 |
-
|
| 124 |
-
|
| 125 |
-
logger.info(f"Converted to {len(dict_messages)} dict messages")
|
| 126 |
|
|
|
|
| 127 |
try:
|
| 128 |
-
response = self.client.
|
| 129 |
-
|
|
|
|
| 130 |
max_tokens=max_tokens,
|
| 131 |
temperature=temperature,
|
| 132 |
stop=stop_sequences,
|
| 133 |
**kwargs
|
| 134 |
)
|
| 135 |
-
|
| 136 |
-
logger.info(f"Generated response length: {len(content)}")
|
| 137 |
-
return content
|
| 138 |
except Exception as e:
|
| 139 |
-
logger.error(f"
|
| 140 |
-
raise Exception(f"
|
| 141 |
|
| 142 |
# ---------- Assemble the Agent ----------
|
| 143 |
tools = [calculator]
|
|
@@ -148,7 +135,7 @@ try:
|
|
| 148 |
except ImportError:
|
| 149 |
logger.warning("β οΈ duckduckgo-search not installed, web_search disabled.")
|
| 150 |
|
| 151 |
-
model =
|
| 152 |
agent = CodeAgent(tools=tools, model=model)
|
| 153 |
|
| 154 |
# ---------- Class Expected by app.py ----------
|
|
|
|
| 4 |
import logging
|
| 5 |
from smolagents import CodeAgent, tool
|
| 6 |
from smolagents.models import Model
|
| 7 |
+
import openai
|
| 8 |
|
| 9 |
# Set up logging
|
| 10 |
logging.basicConfig(level=logging.INFO)
|
| 11 |
logger = logging.getLogger(__name__)
|
| 12 |
|
| 13 |
+
# ---------- Validate OpenAI API Key ----------
|
| 14 |
+
openai_api_key = os.getenv("OPENAI_API_KEY")
|
| 15 |
+
if openai_api_key:
|
| 16 |
+
logger.info(f"β
OPENAI_API_KEY is set (first 4 chars: {openai_api_key[:4]}...)")
|
| 17 |
else:
|
| 18 |
+
logger.error("β OPENAI_API_KEY environment variable is NOT set. Please add it in Space secrets.")
|
| 19 |
+
raise ValueError("OPENAI_API_KEY is required for inference. Stopping startup.")
|
| 20 |
|
| 21 |
# ---------- Answer Cache ----------
|
| 22 |
CACHE_FILE = "answer_cache.json"
|
|
|
|
| 78 |
except Exception as e:
|
| 79 |
return f"Search error: {e}"
|
| 80 |
|
| 81 |
+
# ---------- Custom Model using OpenAI ----------
|
| 82 |
+
class OpenAIModel(Model):
|
| 83 |
+
def __init__(self, model="gpt-3.5-turbo", **kwargs):
|
| 84 |
super().__init__(**kwargs)
|
| 85 |
+
self.client = openai.OpenAI(api_key=openai_api_key)
|
| 86 |
+
self.model = model
|
| 87 |
+
logger.info(f"β
OpenAIModel initialized with model: {model}")
|
| 88 |
|
| 89 |
def generate(
|
| 90 |
self,
|
|
|
|
| 95 |
temperature=0.7,
|
| 96 |
**kwargs
|
| 97 |
):
|
| 98 |
+
# Convert any message format to OpenAI dict format
|
| 99 |
+
openai_messages = []
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 100 |
for msg in messages:
|
| 101 |
if isinstance(msg, str):
|
| 102 |
+
openai_messages.append({"role": "user", "content": msg})
|
|
|
|
| 103 |
elif isinstance(msg, dict):
|
| 104 |
+
# Ensure it has role and content
|
| 105 |
+
role = msg.get("role", "user")
|
| 106 |
+
content = msg.get("content", "")
|
| 107 |
+
openai_messages.append({"role": role, "content": str(content)})
|
|
|
|
|
|
|
|
|
|
| 108 |
elif hasattr(msg, 'role') and hasattr(msg, 'content'):
|
| 109 |
+
openai_messages.append({"role": msg.role, "content": str(msg.content)})
|
|
|
|
| 110 |
else:
|
|
|
|
| 111 |
logger.warning(f"Unknown message type {type(msg)} β converting to string")
|
| 112 |
+
openai_messages.append({"role": "user", "content": str(msg)})
|
|
|
|
|
|
|
| 113 |
|
| 114 |
+
# Prepare API call
|
| 115 |
try:
|
| 116 |
+
response = self.client.chat.completions.create(
|
| 117 |
+
model=self.model,
|
| 118 |
+
messages=openai_messages,
|
| 119 |
max_tokens=max_tokens,
|
| 120 |
temperature=temperature,
|
| 121 |
stop=stop_sequences,
|
| 122 |
**kwargs
|
| 123 |
)
|
| 124 |
+
return response.choices[0].message.content
|
|
|
|
|
|
|
| 125 |
except Exception as e:
|
| 126 |
+
logger.error(f"OpenAI API error: {e}")
|
| 127 |
+
raise Exception(f"OpenAI model {self.model} inference failed: {e}")
|
| 128 |
|
| 129 |
# ---------- Assemble the Agent ----------
|
| 130 |
tools = [calculator]
|
|
|
|
| 135 |
except ImportError:
|
| 136 |
logger.warning("β οΈ duckduckgo-search not installed, web_search disabled.")
|
| 137 |
|
| 138 |
+
model = OpenAIModel() # you can change to "gpt-4" if desired
|
| 139 |
agent = CodeAgent(tools=tools, model=model)
|
| 140 |
|
| 141 |
# ---------- Class Expected by app.py ----------
|