A standardized framework for building gRPC-based AI agents that integrate seamlessly with Telegram bots. AnyAgent provides a complete SDK for handling all Telegram message types, payments, and interactive UI components.
pip install anyagent-aifrom anyagent import BaseAgent, AgentResponse, TelegramMessage, TextContent
class MyAgent(BaseAgent):
async def execute(self, request):
# Echo back any text message
if request.telegram_message and request.telegram_message.text:
text = request.telegram_message.text.text
yield AgentResponse(
telegram_message=TelegramMessage(
text=TextContent(text=f"You said: {text}")
)
)
# Run the agent
if __name__ == "__main__":
from anyagent import AgentServer
agent = MyAgent()
server = AgentServer(agent)
server.run(port=50051)AnyAgent uses a gRPC-based architecture where:
- Telegram Bot Server receives messages from users
- Bot Server converts them to gRPC requests
- Your Agent processes requests and returns responses
- Bot Server sends responses back to Telegram
Telegram User <-> Telegram API <-> Bot Server <-> gRPC <-> Your Agent
All agents inherit from BaseAgent and implement the execute method:
from anyagent import BaseAgent, AgentRequest, AgentResponse
class MyAgent(BaseAgent):
async def execute(self, request: AgentRequest) -> AsyncGenerator[AgentResponse, None]:
# Process request and yield responses
passEvery request contains:
telegram_message: Incoming message (text, image, video, etc.)callback_query: Button press eventsreply_message: When user replies to a messagecontext: Conversation history and metadatapaid: Payment statuslanguage_code: User's languageuser_id: Unique user identifier
Responses can contain:
telegram_message: Message to send backpayment_request: Request payment from usermemory: Store conversation context
from anyagent import TelegramMessage, TextContent
yield AgentResponse(
telegram_message=TelegramMessage(
text=TextContent(text="Hello, World!")
)
)from anyagent import ImageContent
yield AgentResponse(
telegram_message=TelegramMessage(
image=ImageContent(
image_data=image_bytes,
caption="A beautiful image",
filename="image.jpg"
)
)
)from anyagent import VideoContent
yield AgentResponse(
telegram_message=TelegramMessage(
video=VideoContent(
video_data=video_bytes,
caption="Check out this video",
filename="video.mp4"
)
)
)from anyagent import AudioContent
yield AgentResponse(
telegram_message=TelegramMessage(
audio=AudioContent(
audio_data=audio_bytes,
filename="audio.mp3"
)
)
)from anyagent import DocumentContent
yield AgentResponse(
telegram_message=TelegramMessage(
document=DocumentContent(
file_data=file_bytes,
filename="document.pdf"
)
)
)from anyagent import LocationContent
yield AgentResponse(
telegram_message=TelegramMessage(
location=LocationContent(
latitude=37.7749,
longitude=-122.4194
)
)
)Create interactive buttons for users:
from anyagent import InlineKeyboard, InlineButtonRow, InlineButton
keyboard = InlineKeyboard(rows=[
InlineButtonRow(buttons=[
InlineButton.callback_button("β
Accept", "accept"),
InlineButton.callback_button("β Decline", "decline")
]),
InlineButtonRow(buttons=[
InlineButton.url_button("π Documentation", "https://docs.example.com"),
InlineButton.url_button("π Website", "https://example.com")
])
])
yield AgentResponse(
telegram_message=TelegramMessage(
text=TextContent(text="Please choose an option:"),
inline_keyboard=keyboard
)
)async def execute(self, request):
if request.callback_query:
callback_data = request.callback_query.callback_data
if callback_data == "accept":
yield AgentResponse(
telegram_message=TelegramMessage(
text=TextContent(text="You accepted! β
")
)
)
elif callback_data == "decline":
yield AgentResponse(
telegram_message=TelegramMessage(
text=TextContent(text="You declined β")
)
)Request payments for premium features:
from anyagent import UsagePaymentRequest
# Check if user has paid
if not request.paid:
yield AgentResponse(
payment_request=UsagePaymentRequest(
key="premium_feature", # Payment key from web console
quantity=1 # Number of uses
)
)
else:
# Provide premium feature
yield AgentResponse(
telegram_message=TelegramMessage(
text=TextContent(text="Premium feature activated! π")
)
)Store conversation history:
from anyagent import ContextMessage
# Store assistant's response in memory
yield AgentResponse(
telegram_message=TelegramMessage(
text=TextContent(text="I'll remember that!")
),
memory=ContextMessage(
role="assistant",
content="User's favorite color is blue"
)
)
# Access previous context
if request.context:
for message in request.context.messages:
print(f"{message.role}: {message.content}")Show typing indicators:
from anyagent import TelegramAction
yield AgentResponse(
telegram_message=TelegramMessage(
text=TextContent(text="Processing your request..."),
action=TelegramAction.TYPING
)
)Available actions:
TYPING- Shows "typing..." indicatorUPLOADING_PHOTO- Shows "uploading photo..." indicatorUPLOADING_VIDEO- Shows "uploading video..." indicatorUPLOADING_DOCUMENT- Shows "uploading document..." indicatorUPLOADING_AUDIO- Shows "uploading audio..." indicatorRECORDING_VIDEO- Shows "recording video..." indicatorRECORDING_AUDIO- Shows "recording audio..." indicator
For real-time responses:
async def execute(self, request):
# Send initial message
yield AgentResponse(
telegram_message=TelegramMessage(
text=TextContent(text="Processing"),
action=TelegramAction.TYPING
)
)
# Stream updates
for i in range(5):
await asyncio.sleep(1)
yield AgentResponse(
telegram_message=TelegramMessage(
text=TextContent(text=f"Progress: {i+1}/5")
)
)- Create a
Dockerfile:
FROM python:3.10-slim
WORKDIR /app
# Install dependencies
COPY requirements.txt .
RUN pip install -r requirements.txt
# Copy agent code
COPY . .
# Expose gRPC port
EXPOSE 50051
# Run the agent
CMD ["python", "agent.py"]- Create
docker-compose.yml:
version: '3.8'
services:
my_agent:
build: .
ports:
- "50051:50051"
environment:
- GRPC_PORT=50051
restart: unless-stopped- Deploy:
docker-compose up -dGRPC_PORT- Port for gRPC server (default: 50051)MAX_WORKERS- Number of worker threads (default: 10)
class MyAgent(BaseAgent):
async def help(self, request):
"""Custom help command handler"""
yield AgentResponse(
telegram_message=TelegramMessage(
text=TextContent(text="""
π€ MyAgent Help
Commands:
/start - Start the bot
/help - Show this help
/status - Check status
Send me any message and I'll help you!
""")
)
)async def execute(self, request):
try:
# Your logic here
pass
except Exception as e:
yield AgentResponse(
telegram_message=TelegramMessage(
text=TextContent(text=f"β Error: {str(e)}")
)
)import logging
logging.basicConfig(level=logging.INFO)
logger = logging.getLogger(__name__)
class MyAgent(BaseAgent):
async def execute(self, request):
logger.info(f"Received request from user {request.user_id}")
# Your logic here-
"No module named 'anyagent'"
- Solution:
pip install anyagent-ai
- Solution:
-
"Protocol message InlineButton has no 'action' field"
- Solution: Update to anyagent-ai>=1.0.8
- Use
button.HasField('url')instead of checkingactionfield
-
Connection refused on port 50051
- Check if agent is running:
docker ps - Check logs:
docker logs <container_name> - Ensure port is exposed in Dockerfile
- Check if agent is running:
-
Import errors with protobuf
- Solution:
pip install --upgrade protobuf grpcio grpcio-tools
- Solution:
Enable detailed logging:
import logging
logging.getLogger('anyagent').setLevel(logging.DEBUG)Check out the echo_agent directory for a complete example that demonstrates:
- All message types (text, image, video, audio, document, location)
- Interactive keyboards and button handling
- Payment system integration
- Context and memory management
- Streaming responses
- Error handling
- Fork the repository
- Create a feature branch:
git checkout -b feature-name - Commit changes:
git commit -am 'Add feature' - Push to branch:
git push origin feature-name - Submit a pull request
MIT License - see LICENSE file for details.
- Telegram: @saidaziz
- Email: [email protected]
- Issues: GitHub Issues
Built with β€οΈ by the AnyAgent Team