Skip to content

Latest commit

 

History

19 Commits

Folders and files

NameName
Last commit message
Last commit date
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 

Repository files navigation

Mira API Service

A reusable HTTP relay that connects application clients to a Telegram-based AI service through an authenticated Telethon user session.

The service serializes requests through a global queue, sends text or media to the configured Telegram account, collects multi-message and edited responses, and returns a normalized JSON result to the caller.

Engineering highlights

  • HTTP API for text, image, audio, and search-oriented requests
  • Telethon user-session integration
  • Global sequential queue to prevent cross-request response mixing
  • Quiet-window response aggregation
  • Collection of multiple and edited Telegram messages
  • Media passthrough in structured results
  • First-response and overall timeouts
  • Flood-wait handling with a configurable hard limit
  • Optional API-key authentication
  • Proxy support for Telegram connectivity
  • Structured logging with credential sanitization
  • Reusable asynchronous Python client

Technology

Python · FastAPI · Telethon · AsyncIO · Pydantic · HTTPX · Structured Logging

Architecture

Caller application
       │
       ▼
Mira API Service
       │
       ├── request validation
       ├── authentication
       ├── global sequential queue
       └── timeout and response collector
                    │
                    ▼
             Telethon session
                    │
                    ▼
            configured Telegram AI
                    │
                    ▼
       text/media response aggregation
                    │
                    ▼
            normalized JSON response

The sequential queue is intentional: Telegram responses do not carry an application-level correlation ID, so concurrent conversations through one account can otherwise become mixed.

API surface

  • GET /health
  • GET /ready
  • GET /v1/capabilities
  • POST /v1/relay
  • POST /v1/text
  • POST /v1/image
  • POST /v1/audio
  • POST /v1/search

See docs/API.md for request and response schemas.

Quick start

python -m venv .venv
source .venv/bin/activate
pip install .
cp .env.example .env

Configure the Telegram API credentials and string session, then run:

mira-telegram-service-api

Required configuration

TG_API_ID=...
TG_API_HASH=...
TG_STRING_SESSION=...

Important optional settings include:

MIRA_USERNAME=@mira
MIRA_SERVICE_API_KEY=CHANGE_ME
QUIET_WINDOW_SECONDS=4
FIRST_RESPONSE_TIMEOUT_SECONDS=60
OVERALL_TIMEOUT_SECONDS=240
FLOODWAIT_HARD_LIMIT_SECONDS=120
MIRA_MAX_PAYLOAD_MB=20
MIRA_API_HOST=0.0.0.0
MIRA_API_PORT=8090

Proxy connectivity can be enabled with the TG_PROXY_* settings. Both host and port are required when proxy mode is active.

Python client example

import asyncio

from mira_telegram_service.client import MiraServiceClient
from mira_telegram_service.models import InputType, RequestPayload


async def main() -> None:
    client = MiraServiceClient(
        "http://127.0.0.1:8090",
        api_key=None,
        timeout_seconds=320,
    )
    await client.start()
    try:
        result = await client.relay(
            RequestPayload(
                request_id="demo-1",
                bale_user_id="user-1",
                bale_chat_id="chat-1",
                input_type=InputType.TEXT,
                text="Return a short response.",
            )
        )
        print(result.text)
    finally:
        await client.close()


asyncio.run(main())

Response collection

The collector waits for the first response, then continues observing the conversation until a configurable quiet period passes. This supports services that:

  • send several messages for one request
  • edit an initial message with a final answer
  • return one or more media items
  • take longer for search or media processing

The overall timeout still bounds total request duration.

Reliability and isolation

  • one active upstream conversation per configured account
  • bounded payload size
  • first-message and total deadlines
  • FloodWait limits
  • request IDs preserved in service results
  • temporary media cleanup
  • redacted logs
  • readiness checks for session and upstream availability

For higher concurrency, run separate isolated service instances with separate Telegram sessions rather than sharing one account across concurrent workers.

Security notes

  • Never commit API hashes, string sessions, bot tokens, or proxy credentials.
  • Treat the Telegram string session as a password-equivalent secret.
  • Enable service API-key authentication outside isolated local use.
  • Restrict the service to trusted networks.
  • Avoid logging user media, full prompts, or upstream responses unless explicitly required.
  • Rotate credentials immediately after suspected exposure.
  • Ensure use of the upstream Telegram service complies with its terms and access rules.

Project status

Mira API Service demonstrates asynchronous API design, serialized external integration, Telegram session management, response aggregation, media handling, timeout control, and reusable client packaging.

About

Serialized API relay service for forwarding requests to a conversational backend, aggregating responses, and protecting session ordering through a lightweight HTTP interface.

Topics

Resources

Stars

1 star

Watchers

0 watching

Forks

Releases

Packages

Contributors

Languages