Wrapper To Create Telegram Agent Written in Small Agents Framework
Project description
Smol Agents Telegram Bot Wrapper (SmolAgentsTelegram)
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.
The core idea is that the agent sends its final response back to the user by calling a special tool provided by the wrapper, rather than just returning text.
Overview
This project (SmolAgentsTelegram) provides a start_agent_bot function that handles the underlying python-telegram-bot setup. You need to provide:
- Your Telegram Bot Token.
- A function (
generate_agent_fn) that creates and returns asmolagentsagent instance.
New in this version:
- The wrapper now injects a special
on_messagetool into your agent via thegenerate_agent_fn. - Your agent must be configured to use this
on_messagetool to send its final reply back to the Telegram user. - Your
generate_agent_fnfunction must accepton_messageanduser_idarguments and include theon_messageobject in the agent's tool list.
The wrapper automatically manages different agent instances for each unique Telegram chat ID and handles sending the message via the tool. It also includes an optional feature to restrict bot access and a /get_chat_id command.
Features
- Easy Integration: Seamlessly integrates with the
smolagentsframework. - Tool-Based Response: Agents respond by calling a dedicated
on_messagetool, allowing for more complex interactions or asynchronous replies. - PyPI Package: Simple installation via
pip. - 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.
- 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_idcommand for users to easily find their chat ID. - Extensible: Easily customize the type of agent, tools, and models used within the
smolagentsframework.
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).
Installation
-
Create and activate a virtual environment (recommended):
python -m venv venv # On Windows venv\Scripts\activate # On macOS/Linux source venv/bin/activate
-
Install the package from PyPI:
pip install SmolAgentsTelegram
This will install the wrapper and its dependencies, including
smolagentsandpython-telegram-bot. -
(Optional) For Development: If you want to modify the wrapper code itself, clone the repository and install it in editable mode:
git clone <your-repo-url> cd <your-repo-directory> pip install -e .
Configuration
- Create a file named
.envin the root directory of your project where you'll run the bot. - Add your Telegram Bot Token to the
.envfile:TELEGRAM_TOKEN="YOUR_TELEGRAM_BOT_TOKEN_HERE"
- (Optional) Add other required API keys (e.g.,
HUGGINGFACE_HUB_TOKEN).
Usage
-
Create your main Python script (e.g.,
run_bot.py). Note the changes ingenerate_clientfunction signature and how theon_messagetool is used.# run_bot.py import os from dotenv import load_dotenv # Import from the installed SmolAgentsTelegram 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() # --- IMPORTANT CHANGES --- # Your function MUST accept 'on_message' and 'user_id' arguments. # 'on_message' is a dynamically generated tool that the agent MUST use to reply. def generate_client(on_message, user_id): """ Creates a CodeAgent configured to use the provided on_message tool for replies. """ print(f"Creating new agent for user_id: {user_id}") # Configure the model model = HfApiModel(model_id="google/gemma-3-27b-it") # Ensure access/tokens if needed # Configure standard tools standard_tools = [DuckDuckGoSearchTool()] # --- IMPORTANT --- # Add the provided 'on_message' tool to the agent's tool list. # The agent needs to be prompted or instructed to call this tool # (named 'on_message' with description 'this is the function that MUST be used...') # to send its final answer to the user. all_tools = standard_tools + [on_message] # Create the agent with all tools agent = CodeAgent(tools=all_tools, model=model) # Consider adding instructions to your agent's system prompt to use the 'on_message' tool for final replies. return agent if __name__ == "__main__": telegram_token = os.environ.get("TELEGRAM_TOKEN") if not telegram_token: raise ValueError("TELEGRAM_TOKEN not found. Did you create a .env file?") # Optional: Restrict Access (no changes here) # allowed_chat_ids = ["123456789", "987654321"] # start_agent_bot(telegram_token=telegram_token, generate_agent_fn=generate_client, telegram_chat_ids=allowed_chat_ids) print("Starting Telegram bot...") # Pass the updated generate_client function start_agent_bot( telegram_token=telegram_token, generate_agent_fn=generate_client # Corrected function name used here )
-
Instruct Your Agent: You must ensure your agent (through its system prompt or specific instructions within the conversation) understands that it needs to call the
on_messagetool to send the final reply to the user. The tool's description ("this is the function that MUST be used to send final answer back to a cusotmer") is designed to help with this. -
Run the script:
python run_bot.py -
Interact with your bot on Telegram:
- Send a message. You might receive an initial, immediate reply (from the
update.message.reply_text(clt.run(...))line in the wrapper). This likely contains the agent's raw output or thought process. - The final, user-intended response will arrive as a separate message, sent when the agent calls the
on_messagetool. - Use
/get_chat_idto find your chat ID if needed.
- Send a message. You might receive an initial, immediate reply (from the
Customization
- Agent Logic: The main customization is now within your agent's definition and prompting. Ensure it reliably calls the
on_messagetool for its final output. generate_agent_fn: This function must now accepton_messageanduser_idand must include theon_messageobject in the agent'stoolslist.- Tools & Models: You can still customize the other tools and the model used by the agent within
generate_agent_fnas before. - Restricting Access: Pass
telegram_chat_idslist tostart_agent_bot.
License
This project is licensed under the MIT License.
Author
- Viacheslav Kovalevskyi - viacheslav@kovalevskyi.com
Project details
Release history Release notifications | RSS feed
Download files
Download the file for your platform. If you're not sure which to choose, learn more about installing packages.
Source Distribution
Built Distribution
Filter files by name, interpreter, ABI, and platform.
If you're not sure about the file name format, learn more about wheel file names.
Copy a direct link to the current filters
File details
Details for the file smolagentstelegram-1.0.1.tar.gz.
File metadata
- Download URL: smolagentstelegram-1.0.1.tar.gz
- Upload date:
- Size: 5.3 kB
- Tags: Source
- Uploaded using Trusted Publishing? No
- Uploaded via: twine/6.1.0 CPython/3.10.0
File hashes
| Algorithm | Hash digest | |
|---|---|---|
| SHA256 |
9178521741e28ba5b3cf68d05dde385acf6aafb475f6091118ea936063e4cda6
|
|
| MD5 |
c2037ddf80921d0380864415ffb20894
|
|
| BLAKE2b-256 |
dd1f56df049cf490210c4c7c2b338eca07e45aea0aa60719b7bffef65a58de3f
|
File details
Details for the file smolagentstelegram-1.0.1-py3-none-any.whl.
File metadata
- Download URL: smolagentstelegram-1.0.1-py3-none-any.whl
- Upload date:
- Size: 5.1 kB
- Tags: Python 3
- Uploaded using Trusted Publishing? No
- Uploaded via: twine/6.1.0 CPython/3.10.0
File hashes
| Algorithm | Hash digest | |
|---|---|---|
| SHA256 |
3a36cfe920ab4d8d1c4588ad970c07c5d0414c226402c8d41e05be5ccd542ca9
|
|
| MD5 |
d01b876f738319f074971a8fe45a9321
|
|
| BLAKE2b-256 |
211479971b5fba3debe5951b7f9d5fde806b3ac497f42a93b09b23f8ea017195
|