Jovynne commited on
Commit
72ef6a4
·
verified ·
1 Parent(s): 795aaca

Create agent.py

Browse files
Files changed (1) hide show
  1. agent.py +268 -0
agent.py ADDED
@@ -0,0 +1,268 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import os
2
+ from dotenv import load_dotenv
3
+
4
+ # Load environment variables
5
+ load_dotenv()
6
+
7
+ # Try to import real smolagents, fallback to mock
8
+ try:
9
+ from smolagents import ToolCallingAgent, tool
10
+ from smolagents.models import LiteLLMModel
11
+ SMOLAGENTS_AVAILABLE = True
12
+ print("✅ smolagents framework loaded successfully!")
13
+ except ImportError:
14
+ print("⚠️ smolagents not found. Using mock implementation for demonstration.")
15
+ print(" To install: pip install git+https://github.com/huggingface/smolagents.git")
16
+ from mock_smolagents import ToolCallingAgent, tool, LiteLLMModel
17
+ SMOLAGENTS_AVAILABLE = False
18
+
19
+ # Define tools using the decorator (works with both real and mock)
20
+ @tool
21
+ def calculator(expression: str) -> str:
22
+ """Evaluate a mathematical expression.
23
+
24
+ Args:
25
+ expression: A mathematical expression (e.g., '2 + 2 * 3')
26
+
27
+ Returns:
28
+ The result of the evaluation
29
+ """
30
+ try:
31
+ # Safe evaluation
32
+ allowed_chars = set('0123456789+-*/(). ')
33
+ if not all(c in allowed_chars for c in expression):
34
+ return "Error: Only basic math operations allowed: numbers, +, -, *, /, (, ), ."
35
+
36
+ # Use eval with limited scope
37
+ result = eval(expression, {"__builtins__": {}}, {})
38
+ return f"Calculator: {expression} = {result}"
39
+ except Exception as e:
40
+ return f"Calculation error: {str(e)}"
41
+
42
+ @tool
43
+ def search_web(query: str) -> str:
44
+ """Search the web for information.
45
+
46
+ Args:
47
+ query: Search query
48
+
49
+ Returns:
50
+ Search results summary
51
+ """
52
+ try:
53
+ # Try to use duckduckgo if available
54
+ from duckduckgo_search import DDGS
55
+
56
+ results = []
57
+ with DDGS() as ddgs:
58
+ for r in ddgs.text(query, max_results=3):
59
+ results.append(f"• {r['title']}: {r['body'][:100]}...")
60
+
61
+ if results:
62
+ return f"Web search for '{query}':\n" + "\n".join(results)
63
+ return f"No web results found for '{query}'"
64
+ except ImportError:
65
+ return f"[Mock] Web search for '{query}':\n• Result 1: Information about {query}\n• Result 2: More details..."
66
+ except Exception as e:
67
+ return f"Search error: {str(e)}"
68
+
69
+ @tool
70
+ def get_hf_dataset_info(dataset_name: str = "mnist") -> str:
71
+ """Get information about a Hugging Face dataset.
72
+
73
+ Args:
74
+ dataset_name: Name of the dataset (e.g., 'mnist', 'glue')
75
+
76
+ Returns:
77
+ Dataset information
78
+ """
79
+ try:
80
+ from huggingface_hub import get_dataset_info
81
+
82
+ info = get_dataset_info(dataset_name)
83
+ response = f"📊 **Hugging Face Dataset: {info.id}**\n"
84
+ response += f"📥 Downloads: {info.downloads:,}\n"
85
+ response += f"📝 Description: {info.description[:250]}..."
86
+
87
+ return response
88
+ except ImportError:
89
+ datasets = {
90
+ "mnist": "MNIST: 70,000 handwritten digits (28x28 grayscale images), standard computer vision dataset",
91
+ "glue": "GLUE: General Language Understanding Evaluation benchmark for natural language understanding"
92
+ }
93
+ info = datasets.get(dataset_name.lower(), f"Dataset '{dataset_name}' not found in mock database")
94
+ return f"📊 **Dataset Info (Mock):**\n{info}"
95
+ except Exception as e:
96
+ return f"Error getting dataset info: {str(e)}"
97
+
98
+ @tool
99
+ def translate_text(text: str, target_language: str = "Spanish") -> str:
100
+ """Translate text to another language.
101
+
102
+ Args:
103
+ text: Text to translate
104
+ target_language: Target language (default: Spanish)
105
+
106
+ Returns:
107
+ Translated text
108
+ """
109
+ translations = {
110
+ "hello": {
111
+ "spanish": "hola",
112
+ "french": "bonjour",
113
+ "german": "hallo",
114
+ "italian": "ciao"
115
+ },
116
+ "world": {
117
+ "spanish": "mundo",
118
+ "french": "monde",
119
+ "german": "welt",
120
+ "italian": "mondo"
121
+ },
122
+ "goodbye": {
123
+ "spanish": "adiós",
124
+ "french": "au revoir",
125
+ "german": "auf wiedersehen",
126
+ "italian": "addio"
127
+ }
128
+ }
129
+
130
+ text_lower = text.lower()
131
+ lang_lower = target_language.lower()
132
+
133
+ if text_lower in translations and lang_lower in translations[text_lower]:
134
+ return f"Translation: '{text}' → {target_language}: '{translations[text_lower][lang_lower]}'"
135
+ else:
136
+ return f"No translation found for '{text}' to {target_language}. Try: 'hello', 'world', or 'goodbye'"
137
+
138
+ class MyHuggingFaceAgent:
139
+ def __init__(self, use_mock_model=False):
140
+ """Initialize the agent.
141
+
142
+ Args:
143
+ use_mock_model: Use mock model instead of real API (for testing)
144
+ """
145
+ self.use_mock_model = use_mock_model or not SMOLAGENTS_AVAILABLE
146
+
147
+ # Get all tools
148
+ self.tools = [calculator, search_web, get_hf_dataset_info, translate_text]
149
+
150
+ # Initialize the agent
151
+ self.agent = self._create_agent()
152
+
153
+ print(f"Agent initialized with {len(self.tools)} tools")
154
+ print(f"smolagents available: {SMOLAGENTS_AVAILABLE}")
155
+
156
+ def _create_agent(self):
157
+ """Create the smolagents agent."""
158
+ try:
159
+ if self.use_mock_model or not SMOLAGENTS_AVAILABLE:
160
+ # Use mock model
161
+ model = LiteLLMModel(
162
+ model_id="mock-model",
163
+ api_key="mock-key"
164
+ )
165
+ else:
166
+ # Use real model (requires API key)
167
+ api_key = os.getenv("OPENAI_API_KEY") or os.getenv("HF_TOKEN")
168
+ if api_key and api_key != "not-provided":
169
+ model = LiteLLMModel(
170
+ model_id="gpt-3.5-turbo",
171
+ api_key=api_key
172
+ )
173
+ else:
174
+ print("⚠️ No API key found. Using mock model.")
175
+ model = LiteLLMModel(
176
+ model_id="mock-model",
177
+ api_key="mock-key"
178
+ )
179
+
180
+ # Create agent
181
+ agent = ToolCallingAgent(
182
+ model=model,
183
+ tools=self.tools,
184
+ max_steps=5,
185
+ verbose=True,
186
+ add_base_tools=False
187
+ )
188
+
189
+ return agent
190
+
191
+ except Exception as e:
192
+ print(f"Error creating agent: {e}")
193
+ # Return a basic agent as fallback
194
+ return None
195
+
196
+ def run(self, task: str) -> str:
197
+ """Run the agent on a task."""
198
+ try:
199
+ if self.agent:
200
+ # Use smolagents agent
201
+ result = self.agent.run(task)
202
+
203
+ # Format the response
204
+ response = "🤖 **AI Agent Response (smolagents Framework)**\n\n"
205
+ response += f"{result}\n\n"
206
+ response += "---\n"
207
+ response += "🛠️ **Framework:** smolagents (Hugging Face)\n"
208
+ response += f"📊 **Status:** {'Using real framework' if SMOLAGENTS_AVAILABLE else 'Using mock for demonstration'}"
209
+
210
+ return response
211
+ else:
212
+ # Fallback to simple processing
213
+ return self._simple_agent(task)
214
+
215
+ except Exception as e:
216
+ return f"⚠️ **Agent Error:** {str(e)}\n\n{self._simple_agent(task)}"
217
+
218
+ def _simple_agent(self, task: str) -> str:
219
+ """Simple fallback agent."""
220
+ response = "🔧 **Simple Agent Response**\n\n"
221
+
222
+ # Try each tool
223
+ for tool_func in self.tools:
224
+ tool_name = tool_func.name
225
+ if tool_name in task.lower():
226
+ try:
227
+ # Simple argument extraction
228
+ if tool_name == "calculator":
229
+ import re
230
+ expr = re.sub(r'[^\d\+\-\*\/\(\)\.\s]', '', task).strip()
231
+ if expr:
232
+ result = tool_func(expr)
233
+ else:
234
+ result = "Please provide a math expression"
235
+ elif tool_name == "search_web":
236
+ query = task.replace("search", "").replace("find", "").strip()
237
+ result = tool_func(query if query else task)
238
+ elif tool_name == "get_hf_dataset_info":
239
+ result = tool_func()
240
+ elif tool_name == "translate_text":
241
+ if " to " in task.lower():
242
+ parts = task.lower().split(" to ")
243
+ text = parts[0].replace("translate", "").strip()
244
+ lang = parts[1].strip().title()
245
+ result = tool_func(text, lang)
246
+ else:
247
+ result = tool_func("hello")
248
+ else:
249
+ result = tool_func(task)
250
+
251
+ response += f"**{tool_name.replace('_', ' ').title()}:**\n{result}\n\n"
252
+ break
253
+ except Exception as e:
254
+ response += f"Error using {tool_name}: {str(e)}\n\n"
255
+ else:
256
+ # No tool matched
257
+ response += """**I can help with:**
258
+ 1. **Calculator** - Perform math calculations
259
+ Example: 'calculate 15 * 3' or 'what is 45 + 23?'
260
+ 2. **Web Search** - Search for information
261
+ Example: 'search for AI news' or 'find machine learning tutorials'
262
+ 3. **Dataset Info** - Get Hugging Face dataset information
263
+ Example: 'tell me about mnist dataset' or 'glue dataset info'
264
+ 4. **Translation** - Translate words
265
+ Example: 'translate hello to Spanish' or 'translate goodbye to French'
266
+ Try one of these commands!"""
267
+
268
+ return response