Build a Telegram weather bot

Build a Telegram bot that answers weather questions in French, preserves the current conversation, and resets it when the user sends /new. You will test the agent and bot locally, then deploy the agent to Mistral without changing the bot code.

Demonstrates: sessions and turns (idempotency keys, a message sent while a turn runs), tools, serving and deploying an agent.

Run (after the setup below), from the example's folder: uv run --frozen --env-file .env python bot.py

How it works

How it works

Telegram sends each text message to bot.py. The bot opens one session for the chat, forwards the message, and sends the agent's reply back to Telegram. The session retains the conversation until the user sends /new, or until the session ends: the next message then starts a new one.

The bot sends each message with its Telegram message id as the idempotency key, so the same message delivered twice starts one turn. It ignores edited messages, which keep their id.

Telegram chat → bot.py → session → weather agent → get_weather()

The get_weather() tool reads the current weather from Open-Meteo, which is free and needs no API key: it finds the city, then reads the sky, the temperature and the wind.

During local development, agents serve runs the agent on your computer. After deployment, Mistral runs the agent instead. The bot code does not change; you only update the agent name in .env.

The Telegram bot's code

The Telegram bot's code

The example has two projects: the agent in agent/, and the Telegram bot at the root.

FileWhat it shows
agent/main.pyThe whole agent: a typed @agents.tool, and the agent object the CLI loads
agent/run_agent.pyA one-shot in-process run that imports that same agent object
agent_client.pyStarting and ending a session, sending a message, and reading the reply
bot.pyTelegram handlers: one session id per chat, kept across restarts, /new reset, allowed-user check
agent/DockerfileThe image a managed deployment builds

The example's README.md has the full setup and chat script.

The agent is one tool and one Agent. The tool needs httpx, which agent/pyproject.toml lists:

import httpx

from mistralai import agents


def sky(code: int) -> str:
    """Open-Meteo's weather code (WMO) in words."""
    if code <= 3:
        return ["clear sky", "mainly clear", "partly cloudy", "overcast"][code]
    for below, words in [(50, "fog"), (60, "drizzle"), (70, "rain"), (80, "snow"), (95, "rain showers")]:
        if code < below:
            return words
    return "thunderstorm"


@agents.tool
async def get_weather(city: str) -> dict[str, str | float]:
    """Return the current weather in a city: the sky, the temperature and the wind."""
    async with httpx.AsyncClient(timeout=10) as http:  # Open-Meteo is free and needs no key
        found = await http.get("https://geocoding-api.open-meteo.com/v1/search", params={"name": city, "count": 1})
        if not (places := found.json().get("results")):
            raise agents.ToolError(f"No city named {city}.")
        place = places[0]
        forecast = await http.get(
            "https://api.open-meteo.com/v1/forecast",
            params={
                "latitude": place["latitude"],
                "longitude": place["longitude"],
                "current": "weather_code,temperature_2m,wind_speed_10m",
            },
        )
    now = forecast.json()["current"]
    return {
        "city": f"{place['name']}, {place.get('country', '')}",
        "sky": sky(now["weather_code"]),
        "temperature_celsius": now["temperature_2m"],
        "wind_km_per_hour": now["wind_speed_10m"],
    }


# Replace `alice` with a unique lowercase identifier, such as your GitHub handle,
# so the served and deployed names cannot collide with anyone else's.
agent = agents.Agent(
    model="mistral-large-4",
    name="french-weather-agent-alice-local",
    instructions=(
        "Always answer in French. "
        "When the user asks about weather in a city, call get_weather first. "
        "Keep the answer concise."
    ),
    tools=[get_weather],
)

The bot stores only a session id per chat. ask sends each Telegram message with its message id as the idempotency key. When a message arrives while a turn runs, send_message steers that turn (turn.started is False), and that turn's reply answers both:

import contextlib

from mistralai import agents


def connect(agent_name: str) -> agents.Agent:
    return agents.Agent.load_from(agent_name=agent_name)


async def start_conversation(agent: agents.Agent) -> str:
    """Start a session and return its id, the only thing the bot stores."""
    session = await agent.start_session()
    return session.id


async def end_conversation(agent: agents.Agent, session_id: str) -> None:
    # A session that already ended is left as it is; one its host no longer has needs nothing.
    with contextlib.suppress(agents.SessionNotFoundError):
        await agent.session(session_id).cancel()


async def ask(agent: agents.Agent, session_id: str, text: str, message_id: int) -> str | None:
    """Send one Telegram message to the conversation and return the agent's reply.

    Returns None when the message steered a turn that was already running: that turn's reply
    answers it.
    """
    session = agent.session(session_id)
    # The same Telegram message, delivered again after a restart, is sent once.
    turn = await session.send_message(text, idempotency_key=f"telegram:{message_id}")
    if not turn.started:
        return None
    match await turn.result():
        case agents.Completed(text=reply) if reply:
            return reply
        case state:
            raise RuntimeError(f"The turn did not complete with a reply: {state!r}")
Prerequisites

Prerequisites

You need:

  • Python 3.12 and uv.
  • A Mistral API key whose user has a workspace role with Workflows access, such as Developer: see Deploy. agents serve and agents deploy both require it.
  • A Telegram account.
  • To deploy the agent: a GitHub repository that you grant access to through the GitHub connector in Mistral Studio. You can complete the local steps without it.
1. Try the agent

1. Try the agent

From the agent/ project, copy .env.example to .env and set MISTRAL_API_KEY in it. Then install and inspect what the CLI discovers:

cd agent
cp .env.example .env
uv sync
uv run --frozen --env-file .env agents info

agents info lists the agent and its get_weather tool. Then run it once from Python before adding Telegram:

uv run --frozen --env-file .env python run_agent.py

run_agent.py imports the same agent object out of main.py that the CLI loads, so the script and the served agent cannot drift. It prints a short French answer with Paris's weather at that moment:

Output
Voici la météo actuelle à Paris :
• ☁️ Ciel : couvert
• 🌡️ Température : 7,6 °C
• 💨 Vent : 7,6 km/h
2. Serve the agent

2. Serve the agent

bot.py runs separately from the agent, so it cannot use the in-process Agent object from step

  1. Start the agent with agents serve so the bot can open sessions against it:
uv run --frozen --env-file .env agents serve

The command registers the agent with Mistral Workflows, runs it on your computer, and prints links to chat with it or inspect its runs. Keep the command running while you test the Telegram bot.

Mistral identifies served and deployed agents by name. The example uses alice as a placeholder: replace it with a unique lowercase identifier, such as your GitHub handle, everywhere it appears.

3. Run the bot

3. Run the bot

Create a bot with Telegram's verified @BotFather account (/newbot, pick a name and a username ending in bot, copy the token). Keep the token secret: anyone who has it can control your bot.

Back in the telegram_weather_bot/ directory, copy .env.example to .env and fill in the bot token, your Mistral API key, and the agent name. TELEGRAM_ALLOWED_USER_ID stays at 0 until the first run — the bot's /id command tells you your Telegram user ID, and the check stops other users from talking to your agent.

uv sync
uv run --frozen --env-file .env python bot.py

In your direct chat with the bot, send /id, put the number into TELEGRAM_ALLOWED_USER_ID, restart the bot, then:

/start
Quel temps fait-il à Paris ?
Souviens-toi que ma ville préférée est Lyon.
Quelle est ma ville préférée ?
/new
Quelle est ma ville préférée ?

The weather answer should be in French. The agent should remember Lyon within that session. After /new, it should no longer know which city you chose.

4. Deploy the agent to Mistral

4. Deploy the agent to Mistral

The bot depends on agents serve running on your computer. A managed deployment builds the agent from Git — push agent/ to a repository the GitHub connector can read (never commit .env), then deploy without the -local suffix:

cd agent
uv run --frozen --env-file .env \
  agents deploy . --name french-weather-agent-alice

The locally served agent and managed deployment share a Mistral workspace, where names are unique. Using french-weather-agent-alice-local locally and french-weather-agent-alice for the deployment keeps the two registrations from colliding.

Stop agents serve, change AGENT_NAME in the bot's .env to the deployed name, and restart bot.py. If the bot still answers, it is using the agent hosted by Mistral. Only the agent is deployed; bot.py still runs on your computer.

To update the deployment, push the change and deploy again with the same name — reusing a name updates that deployment, a different one creates a separate deployment.

Inspect sessions in Mistral Studio

Inspect sessions in Mistral Studio

Sessions handled by agents started with either agents serve or agents deploy appear in Agent sessions in Mistral Studio. Open a session to review its messages, tool calls, and status.

Troubleshooting

Troubleshooting

agents serve cannot register the agent

agents serve cannot register the agent

Check that MISTRAL_API_KEY is valid and that its user has a workspace role with Workflows access (see Deploy for the roles). A key that can call a model may still lack permission to register the agent.

uv run --frozen cannot find uv.lock

uv run --frozen cannot find uv.lock

Run uv sync once in that project, then retry the command.

The Telegram bot does not answer

The Telegram bot does not answer

Keep bot.py running. While testing locally, keep agents serve running too. Send messages in a direct chat, confirm TELEGRAM_ALLOWED_USER_ID matches /id, and check AGENT_NAME. Restart the bot after changing .env, then inspect its terminal for the reported error.

Telegram reports a polling conflict

Telegram reports a polling conflict

Only one bot.py process can poll with a bot token. Stop the other process and restart this one.

The managed deployment cannot read the source

The managed deployment cannot read the source

Confirm that the commit is pushed to the repository you granted the GitHub connector access to, and that the connector is enabled in Mistral Studio.

Resources and next steps

Resources and next steps

  • Majordome is a bot that messages you first: it checks your mail and calendar five times a day, follows every event of a long-lived session, and waits for your tap on Allow before each write. Its setup follows the steps on this page.
  • Sessions explains the sessions bot.py keeps per chat and their conversation history.
  • Tools shows how to add a second tool next to get_weather.
  • Run modes compares running the agent in your process with deploying it with Studio (self-hosted or Mistral-managed), and documents what the CLI loads from a project.