Close Menu
    DevStackTipsDevStackTips
    • Home
    • News & Updates
      1. Tech & Work
      2. View All

      This week in AI updates: Mistral’s new Le Chat features, ChatGPT updates, and more (September 5, 2025)

      September 6, 2025

      Designing For TV: Principles, Patterns And Practical Guidance (Part 2)

      September 5, 2025

      Neo4j introduces new graph architecture that allows operational and analytics workloads to be run together

      September 5, 2025

      Beyond the benchmarks: Understanding the coding personalities of different LLMs

      September 5, 2025

      Development Release: KDE Linux 20250906

      September 6, 2025

      Hitachi Energy Pledges $1B to Strengthen US Grid, Build Largest Transformer Plant in Virginia

      September 5, 2025

      How to debug a web app with Playwright MCP and GitHub Copilot

      September 5, 2025

      Between Strategy and Story: Thierry Chopain’s Creative Path

      September 5, 2025
    • Development
      1. Algorithms & Data Structures
      2. Artificial Intelligence
      3. Back-End Development
      4. Databases
      5. Front-End Development
      6. Libraries & Frameworks
      7. Machine Learning
      8. Security
      9. Software Engineering
      10. Tools & IDEs
      11. Web Design
      12. Web Development
      13. Web Security
      14. Programming Languages
        • PHP
        • JavaScript
      Featured

      Health Monitoring Android App using SQLite

      September 7, 2025
      Recent

      Health Monitoring Android App using SQLite

      September 7, 2025

      Convertedbook – Live LaTeX Preview in the Browser

      September 7, 2025

      Why browsers throttle JavaScript timers (and what to do about it)

      September 6, 2025
    • Operating Systems
      1. Windows
      2. Linux
      3. macOS
      Featured

      Speed Isn’t Everything When Buying SSDs – Here’s What Really Matters!

      September 8, 2025
      Recent

      Speed Isn’t Everything When Buying SSDs – Here’s What Really Matters!

      September 8, 2025

      14 Themes for Beautifying Your Ghostty Terminal

      September 8, 2025

      Development Release: KDE Linux 20250906

      September 6, 2025
    • Learning Resources
      • Books
      • Cheatsheets
      • Tutorials & Guides
    Home»Development»Machine Learning»Building a Versatile Multi‑Tool AI Agent Using Lightweight Hugging Face Models

    Building a Versatile Multi‑Tool AI Agent Using Lightweight Hugging Face Models

    July 22, 2025

    In this tutorial, we begin by setting up a compact yet capable AI agent that runs smoothly, leveraging Hugging Face transformers. We integrate dialog generation, question‑answering, sentiment analysis, web search stubs, weather look‑ups, and a safe calculator into a single Python class. As we progress, we install only the essential libraries, load lightweight models that respect Colab’s memory limits, and wrap each capability inside tidy, reusable methods. Together, we explore how every component, from intent detection to device-aware model loading, fits into a coherent workflow, empowering us to prototype sophisticated, multi-tool agents.

    Copy CodeCopiedUse a different Browser
    !pip install transformers torch accelerate datasets requests beautifulsoup4
    
    
    import torch
    import json
    import requests
    from datetime import datetime
    from transformers import (
       AutoTokenizer, AutoModelForCausalLM, AutoModelForSequenceClassification,
       AutoModelForQuestionAnswering, pipeline
    )
    from bs4 import BeautifulSoup
    import warnings
    warnings.filterwarnings('ignore')

    We begin by installing the key Python libraries, Transformers, Torch, Accelerate, Datasets, Requests, and BeautifulSoup, so our Colab environment has everything it needs for model loading, inference, and web scraping. Next, we import PyTorch, JSON utilities, HTTP and date helpers, Hugging Face classes for generation, classification, and QA, as well as BeautifulSoup for HTML parsing, while silencing unnecessary warnings to keep the notebook output clean.

    Copy CodeCopiedUse a different Browser
    class AdvancedAIAgent:
       def __init__(self):
           """Initialize the AI Agent with multiple models and capabilities"""
           self.device = "cuda" if torch.cuda.is_available() else "cpu"
           print(f"<img src="https://s.w.org/images/core/emoji/16.0.1/72x72/1f680.png" alt="🚀" class="wp-smiley" /> Initializing AI Agent on {self.device}")
          
           self._load_models()
          
           self.tools = {
               "web_search": self.web_search,
               "calculator": self.calculator,
               "weather": self.get_weather,
               "sentiment": self.analyze_sentiment
           }
          
           print("<img src="https://s.w.org/images/core/emoji/16.0.1/72x72/2705.png" alt="✅" class="wp-smiley" /> AI Agent initialized successfully!")
    
    
       def _load_models(self):
           """Load all required models"""
           print("<img src="https://s.w.org/images/core/emoji/16.0.1/72x72/1f4e5.png" alt="📥" class="wp-smiley" /> Loading models...")
          
           self.gen_tokenizer = AutoTokenizer.from_pretrained("microsoft/DialoGPT-medium")
           self.gen_model = AutoModelForCausalLM.from_pretrained("microsoft/DialoGPT-medium")
           self.gen_tokenizer.pad_token = self.gen_tokenizer.eos_token
          
           self.sentiment_pipeline = pipeline(
               "sentiment-analysis",
               model="cardiffnlp/twitter-roberta-base-sentiment-latest",
               device=0 if self.device == "cuda" else -1
           )
          
           self.qa_pipeline = pipeline(
               "question-answering",
               model="distilbert-base-cased-distilled-squad",
               device=0 if self.device == "cuda" else -1
           )
          
           print("<img src="https://s.w.org/images/core/emoji/16.0.1/72x72/2705.png" alt="✅" class="wp-smiley" /> All models loaded!")
    
    
       def generate_response(self, prompt, max_length=100, temperature=0.7):
           """Generate text response using the language model"""
           inputs = self.gen_tokenizer.encode(prompt + self.gen_tokenizer.eos_token,
                                            return_tensors='pt')
          
           with torch.no_grad():
               outputs = self.gen_model.generate(
                   inputs,
                   max_length=max_length,
                   temperature=temperature,
                   do_sample=True,
                   pad_token_id=self.gen_tokenizer.eos_token_id,
                   attention_mask=torch.ones_like(inputs)
               )
          
           response = self.gen_tokenizer.decode(outputs[0][len(inputs[0]):],
                                              skip_special_tokens=True)
           return response.strip()
    
    
       def analyze_sentiment(self, text):
           """Analyze sentiment of given text"""
           result = self.sentiment_pipeline(text)[0]
           return {
               "sentiment": result['label'],
               "confidence": round(result['score'], 4),
               "text": text
           }
    
    
       def answer_question(self, question, context):
           """Answer questions based on given context"""
           result = self.qa_pipeline(question=question, context=context)
           return {
               "answer": result['answer'],
               "confidence": round(result['score'], 4),
               "question": question
           }
    
    
       def web_search(self, query):
           """Simulate web search (replace with actual API if needed)"""
           try:
               return {
                   "query": query,
                   "results": f"Search results for '{query}': Latest information retrieved successfully.",
                   "timestamp": datetime.now().strftime("%Y-%m-%d %H:%M:%S")
               }
           except Exception as e:
               return {"error": f"Search failed: {str(e)}"}
    
    
       def calculator(self, expression):
           """Safe calculator function"""
           try:
               allowed_chars = set('0123456789+-*/.() ')
               if not all(c in allowed_chars for c in expression):
                   return {"error": "Invalid characters in expression"}
              
               result = eval(expression)
               return {
                   "expression": expression,
                   "result": result,
                   "type": type(result).__name__
               }
           except Exception as e:
               return {"error": f"Calculation failed: {str(e)}"}
    
    
       def get_weather(self, location):
           """Mock weather function (replace with actual weather API)"""
           return {
               "location": location,
               "temperature": "22°C",
               "condition": "Partly cloudy",
               "humidity": "65%",
               "note": "This is mock data. Integrate with a real weather API for actual data."
           }
    
    
       def detect_intent(self, user_input):
           """Simple intent detection based on keywords"""
           user_input = user_input.lower()
          
           if any(word in user_input for word in ['calculate', 'math', '+', '-', '*', '/']):
               return 'calculator'
           elif any(word in user_input for word in ['weather', 'temperature', 'forecast']):
               return 'weather'
           elif any(word in user_input for word in ['search', 'find', 'look up']):
               return 'web_search'
           elif any(word in user_input for word in ['sentiment', 'emotion', 'feeling']):
               return 'sentiment'
           elif '?' in user_input:
               return 'question_answering'
           else:
               return 'chat'
    
    
       def process_request(self, user_input, context=""):
           """Main method to process user requests"""
           print(f"<img src="https://s.w.org/images/core/emoji/16.0.1/72x72/1f916.png" alt="🤖" class="wp-smiley" /> Processing: {user_input}")
          
           intent = self.detect_intent(user_input)
           response = {"intent": intent, "input": user_input}
          
           try:
               if intent == 'calculator':
                   import re
                   expr = re.findall(r'[0-9+-*/.() ]+', user_input)
                   if expr:
                       result = self.calculator(expr[0].strip())
                       response.update(result)
                   else:
                       response["error"] = "No valid mathematical expression found"
              
               elif intent == 'weather':
                   words = user_input.split()
                   location = "your location" 
                   for i, word in enumerate(words):
                       if word.lower() in ['in', 'at', 'for']:
                           if i + 1 < len(words):
                               location = words[i + 1]
                               break
                   result = self.get_weather(location)
                   response.update(result)
              
               elif intent == 'web_search':
                   query = user_input.replace('search', '').replace('find', '').strip()
                   result = self.web_search(query)
                   response.update(result)
              
               elif intent == 'sentiment':
                   text_to_analyze = user_input.replace('sentiment', '').strip()
                   if not text_to_analyze:
                       text_to_analyze = "I'm feeling great today!"
                   result = self.analyze_sentiment(text_to_analyze)
                   response.update(result)
              
               elif intent == 'question_answering' and context:
                   result = self.answer_question(user_input, context)
                   response.update(result)
              
               else:
                   generated_response = self.generate_response(user_input)
                   response["response"] = generated_response
                   response["type"] = "generated_text"
          
           except Exception as e:
               response["error"] = f"Error processing request: {str(e)}"
          
           return response

    Join the fastest growing AI Dev Newsletter read by Devs and Researchers from NVIDIA, OpenAI, DeepMind, Meta, Microsoft, JP Morgan Chase, Amgen, Aflac, Wells Fargo and 100s more…….

    We encapsulate our entire toolkit inside an AdvancedAIAgent class that boots on GPU when available, loads dialogue, sentiment, and QA models, and registers helper tools for search, weather, and arithmetic. With lightweight keyword-based intent detection, we dynamically route each user message to the right pipeline or fall back to free-form generation, providing a unified, multi-skill agent driven by just a few clean methods.

    Copy CodeCopiedUse a different Browser
    if __name__ == "__main__":
       agent = AdvancedAIAgent()
      
       print("n" + "="*50)
       print("<img src="https://s.w.org/images/core/emoji/16.0.1/72x72/1f3af.png" alt="🎯" class="wp-smiley" /> DEMO: Advanced AI Agent Capabilities")
       print("="*50)
      
       test_cases = [
           "Calculate 25 * 4 + 10",
           "What's the weather in Tokyo?",
           "Search for latest AI developments",
           "Analyze sentiment of: I love working with AI!",
           "Hello, how are you today?"
       ]
      
       for test in test_cases:
           print(f"n<img src="https://s.w.org/images/core/emoji/16.0.1/72x72/1f464.png" alt="👤" class="wp-smiley" /> User: {test}")
           result = agent.process_request(test)
           print(f"<img src="https://s.w.org/images/core/emoji/16.0.1/72x72/1f916.png" alt="🤖" class="wp-smiley" /> Agent: {json.dumps(result, indent=2)}")
      
       """
       print("n<img src="https://s.w.org/images/core/emoji/16.0.1/72x72/1f3ae.png" alt="🎮" class="wp-smiley" /> Interactive Mode - Type 'quit' to exit")
       while True:
           user_input = input("n<img src="https://s.w.org/images/core/emoji/16.0.1/72x72/1f464.png" alt="👤" class="wp-smiley" /> You: ")
           if user_input.lower() == 'quit':
               break
          
           result = agent.process_request(user_input)
           print(f"<img src="https://s.w.org/images/core/emoji/16.0.1/72x72/1f916.png" alt="🤖" class="wp-smiley" /> Agent: {json.dumps(result, indent=2)}")
       """
    

    We conclude by spawning the AdvancedAIAgent, announcing a quick demo section, and firing five representative prompts that test calculation, weather, search, sentiment, and open‑ended chat in one sweep. After reviewing the neatly formatted JSON replies, we keep an optional interactive loop on standby, ready for live experimentation whenever we decide to un‑comment it.

    In conclusion, we test a variety of real-world prompts and observe how it handles arithmetic, fetches mock weather data, gauges sentiment, and engages in natural conversation, all through a single unified interface using Hugging Face models. This exercise demonstrates how we can stitch multiple NLP tasks into an extensible framework that remains friendly to Colab resources.


    Check out the Codes. All credit for this research goes to the researchers of this project.

    Join the fastest growing AI Dev Newsletter read by Devs and Researchers from NVIDIA, OpenAI, DeepMind, Meta, Microsoft, JP Morgan Chase, Amgen, Aflac, Wells Fargo and 100s more…….

    The post Building a Versatile Multi‑Tool AI Agent Using Lightweight Hugging Face Models appeared first on MarkTechPost.

    Source: Read More 

    Facebook Twitter Reddit Email Copy Link
    Previous ArticleAre We Ready for Production-Grade Apps With Vibe Coding? A Look at the Replit Fiasco
    Next Article Context Engineering for AI Agents: Key Lessons from Manus

    Related Posts

    Machine Learning

    How to Evaluate Jailbreak Methods: A Case Study with the StrongREJECT Benchmark

    September 3, 2025
    Machine Learning

    Announcing the new cluster creation experience for Amazon SageMaker HyperPod

    September 3, 2025
    Leave A Reply Cancel Reply

    For security, use of Google's reCAPTCHA service is required which is subject to the Google Privacy Policy and Terms of Use.

    Continue Reading

    Cisco warns that Unified CM has hardcoded root SSH credentials

    Security

    CVE-2024-41753 – IBM Cloud Pak for Business Automation Cross-Site Scripting Vulnerability

    Common Vulnerabilities and Exposures (CVEs)

    Bouncer chooses the correct firewall zone for wireless connections

    Linux

    Gwyddion – SPM data visualization and analysis

    Linux

    Highlights

    CISA warns of attackers exploiting Linux flaw with PoC exploit

    June 18, 2025

    CISA warns of attackers exploiting Linux flaw with PoC exploit

    CISA has warned U.S. federal agencies about attackers targeting a high-severity vulnerability in the Linux kernel’s OverlayFS subsystem that allows them to gain root privileges.
    This local privilege e …
    Read more

    Published Date:
    Jun 18, 2025 (3 hours, 1 minute ago)

    Vulnerabilities has been mentioned in this article.

    Firefox Fixes an 8-Year-Old Windows Bug That Broke Virtual Desktop Use

    August 28, 2025

    Best early Prime Day laptop deals: My 12 favorite sales live now

    June 17, 2025

    Intel Prepares Massive Layoffs: Up to 20% of Foundry Division Workforce Cut Starting July 2025

    June 19, 2025
    © DevStackTips 2025. All rights reserved.
    • Contact
    • Privacy Policy

    Type above and press Enter to search. Press Esc to cancel.