Skip to main content

Wrapper To Create Telegram Agent Written in Small Agents Framework

Project description

Smol Agents Telegram Bot Wrapper

License: MIT

A Python wrapper designed to simplify the creation of Telegram bots using the smolagents framework from Hugging Face. This wrapper allows you to quickly deploy agents as Telegram bots, where each user interacts with their own persistent agent instance.

Overview

This project provides a start_agent_bot function that handles the underlying python-telegram-bot setup. You only need to provide:

  1. Your Telegram Bot Token.
  2. A function (generate_agent_fn) that creates and returns a smolagents agent instance (e.g., CodeAgent, AssistantAgent).

The wrapper automatically manages different agent instances for each unique Telegram chat ID, ensuring conversations are isolated between users. It also includes an optional feature to restrict bot access to a predefined list of chat IDs and a command to help users find their chat ID.

Features

  • Easy Integration: Seamlessly integrates with the smolagents framework.
  • Multi-User Support: Automatically creates and manages separate agent instances for each Telegram user (based on chat ID).
  • Stateful Conversations: Each user interacts with their dedicated agent, maintaining conversation context (depending on the agent's implementation).
  • Access Control: Optionally restrict bot usage to specific Telegram chat IDs.
  • Simple Setup: Requires minimal boilerplate code to get a bot running.
  • Helper Command: Includes a /get_chat_id command for users to easily find their chat ID.
  • Extensible: Easily customize the type of agent, tools, and models used within the smolagents framework.

Prerequisites

  • Python 3.8+
  • A Telegram Bot: Create one using BotFather on Telegram to get your TELEGRAM_TOKEN.
  • (Optional) API keys for specific models or tools (e.g., Hugging Face Hub token if using private/gated models via HfApiModel).

Installation

  1. Clone the repository (if you haven't already):

    git clone <your-repo-url>
    cd <your-repo-directory>
    
  2. Create and activate a virtual environment (recommended):

    python -m venv venv
    # On Windows
    venv\Scripts\activate
    # On macOS/Linux
    source venv/bin/activate
    
  3. Install the package and its dependencies: This will install the wrapper itself (sat) along with dependencies listed in requirements.txt (like smolagents, python-telegram-bot, python-dotenv, etc.).

    pip install .
    

    For development, you might prefer an editable install:

    pip install -e .
    

Configuration

  1. Create a file named .env in the root directory of your project.
  2. Add your Telegram Bot Token to the .env file:
    TELEGRAM_TOKEN="YOUR_TELEGRAM_BOT_TOKEN_HERE"
    
  3. (Optional) If your chosen agent/model requires other API keys (like a Hugging Face token for HfApiModel), add them to the .env file as well.
    # Example if needed for private/gated models or rate limits
    # HUGGINGFACE_HUB_TOKEN="YOUR_HF_TOKEN_HERE"
    

Usage

  1. Create your main Python script (e.g., run_bot.py) based on the example provided:

    # run_bot.py
    import os
    from dotenv import load_dotenv
    # Import from this wrapper package
    from sat import start_agent_bot
    # Import from Hugging Face's smolagents
    from smolagents import CodeAgent, DuckDuckGoSearchTool, HfApiModel
    
    # Load environment variables from .env file
    load_dotenv()
    
    # Define a function that creates and returns an agent instance
    # This function will be called for each new user (chat_id)
    def generate_client(user_id):
        """Creates a CodeAgent with Gemma and DuckDuckGo search using smolagents."""
        print(f"Creating new agent for user_id: {user_id}")
        # Configure the model (using HfApiModel from smolagents)
        model = HfApiModel(model_id="google/gemma-3-27b-it") # Ensure access/tokens if needed
    
        # Configure the tools (using DuckDuckGoSearchTool from smolagents)
        tools = [DuckDuckGoSearchTool()]
    
        # Create the agent (using CodeAgent from smolagents)
        agent = CodeAgent(tools=tools, model=model)
        return agent
    
    if __name__ == "__main__":
        # Get the Telegram token from environment variables
        telegram_token = os.environ.get("TELEGRAM_TOKEN")
        if not telegram_token:
            raise ValueError("TELEGRAM_TOKEN not found in environment variables. Did you create a .env file?")
    
        # --- Optional: Restrict Access ---
        # If you want to restrict the bot to certain users, create a list of allowed chat IDs (as strings)
        # allowed_chat_ids = ["123456789", "987654321"]
        # Then pass it to start_agent_bot:
        # start_agent_bot(
        #     telegram_token=telegram_token,
        #     generate_agent_fn=generate_client,
        #     telegram_chat_ids=allowed_chat_ids # Pass the list here
        # )
        # --- End Optional ---
    
        # Start the bot without restrictions
        print("Starting Telegram bot...")
        start_agent_bot(
            telegram_token=telegram_token,
            generate_agent_fn=generate_client
        )
    
  2. Run the script:

    python run_bot.py
    
  3. Interact with your bot on Telegram:

    • Find your bot on Telegram (the one you created with BotFather).
    • Send it messages. Each message will be processed by the smolagents agent instance associated with your chat ID.
    • If you need to find your chat ID (e.g., to add it to the allowed_chat_ids list), send the command /get_chat_id to the bot.

Customization

  • Different Agents: Modify the generate_client function to return a different type of agent available in smolagents.
  • Different Tools: Change the tools list within generate_client to use other tools compatible with smolagents.
  • Different Models: Change the model instance within generate_client. Use other models supported by smolagents (e.g., different HfApiModel configurations, potentially others if the library expands). Remember to configure any necessary API keys.
  • Restricting Access: To limit who can use the bot, create a list of allowed Telegram chat IDs (as strings) and pass it to start_agent_bot using the telegram_chat_ids parameter (see the commented-out section in the example run_bot.py).

License

This project is licensed under the MIT License - see the LICENSE file (if you have one) or the setup.py file for details.

Author

Project details


Download files

Download the file for your platform. If you're not sure which to choose, learn more about installing packages.

Source Distribution

smolagentstelegram-0.0.1.tar.gz (4.7 kB view details)

Uploaded Source

Built Distribution

If you're not sure about the file name format, learn more about wheel file names.

smolagentstelegram-0.0.1-py3-none-any.whl (4.6 kB view details)

Uploaded Python 3

File details

Details for the file smolagentstelegram-0.0.1.tar.gz.

File metadata

  • Download URL: smolagentstelegram-0.0.1.tar.gz
  • Upload date:
  • Size: 4.7 kB
  • Tags: Source
  • Uploaded using Trusted Publishing? No
  • Uploaded via: twine/6.1.0 CPython/3.10.0

File hashes

Hashes for smolagentstelegram-0.0.1.tar.gz
Algorithm Hash digest
SHA256 072cd7fdfc60cc685fa8c03cdee0f52a43666b107227445d33191ac963f248c9
MD5 ea34795746c65983882b656705c9becc
BLAKE2b-256 024102103143cca651defb89e330fe11d2c9919a25fff06192fd54f29f952ce1

See more details on using hashes here.

File details

Details for the file smolagentstelegram-0.0.1-py3-none-any.whl.

File metadata

File hashes

Hashes for smolagentstelegram-0.0.1-py3-none-any.whl
Algorithm Hash digest
SHA256 34abb5b813339b2232b2d8fd7a97bb3f647dfbcbc362b8e9ed09ffad75399a74
MD5 52f2d4a08715537a44f6cf6bcce1a7a3
BLAKE2b-256 05298168309d18e1956bb0a5fd59690c7ca99f6be7c78c1794b47d296286fbd5

See more details on using hashes here.

Supported by

AWS Cloud computing and Security Sponsor Datadog Monitoring Depot Continuous Integration Fastly CDN Google Download Analytics Pingdom Monitoring Sentry Error logging StatusPage Status page