Metadata-Version: 2.4
Name: sector-ai
Version: 2.3.0
Summary: Python Telegram Bot powered by LangChain, Ollama or any OpenAI-compatible endpoint
Author: Rory Eckel
License-Expression: GPL-3.0-only
Project-URL: Homepage, https://github.com/roryeckel/sector-ai
Project-URL: Issues, https://github.com/roryeckel/sector-ai/issues
Project-URL: Changelog, https://github.com/roryeckel/sector-ai/releases
Keywords: telegram,bot,ollama,openai,langchain,llm
Classifier: Programming Language :: Python :: 3
Classifier: Programming Language :: Python :: 3.11
Classifier: Programming Language :: Python :: 3.12
Classifier: Programming Language :: Python :: 3.13
Classifier: Topic :: Communications :: Chat
Classifier: Topic :: Scientific/Engineering :: Artificial Intelligence
Classifier: Operating System :: OS Independent
Requires-Python: >=3.11
Description-Content-Type: text/markdown
License-File: LICENSE
Requires-Dist: langchain-core==1.8.4
Requires-Dist: langchain-ollama==1.1.0
Requires-Dist: langchain-openai==1.8.5
Requires-Dist: langgraph==1.2.24
Requires-Dist: langchain-mcp-adapters==0.3.2
Requires-Dist: jsonschema==4.26.0
Requires-Dist: referencing==0.37.0
Requires-Dist: python-telegram-bot==22.8
Requires-Dist: aiolimiter==1.3.0
Requires-Dist: telegramify-markdown==1.4.2
Requires-Dist: svglib==2.4.0
Requires-Dist: reportlab==5.1.0
Requires-Dist: pypdfium2==5.15.2
Requires-Dist: pydantic==2.14.4
Requires-Dist: pydantic-settings==2.16.3
Requires-Dist: python-dotenv==1.2.4
Requires-Dist: httpx==0.28.1
Requires-Dist: openai==3.57.0
Requires-Dist: httpx2<3,>=2.16.2
Provides-Extra: dev
Requires-Dist: ruff==0.17.6; extra == "dev"
Requires-Dist: pytest==9.2.0; extra == "dev"
Requires-Dist: pytest-asyncio==1.5.0; extra == "dev"
Requires-Dist: pytest-cov==7.1.0; extra == "dev"
Requires-Dist: coverage==7.18.0; extra == "dev"
Requires-Dist: packaging==26.4; extra == "dev"
Dynamic: license-file

# Sector AI Telegram Bot

[![CI](https://github.com/roryeckel/sector-ai/actions/workflows/ci.yml/badge.svg)](https://github.com/roryeckel/sector-ai/actions/workflows/ci.yml)
[![PyPI](https://img.shields.io/pypi/v/sector-ai.svg)](https://pypi.org/project/sector-ai/)
[![Docker](https://img.shields.io/github/v/release/roryeckel/sector-ai?label=ghcr.io&logo=docker&logoColor=white&color=2496ED)](https://github.com/roryeckel/sector-ai/pkgs/container/sector-ai)
[![License](https://img.shields.io/github/license/roryeckel/sector-ai.svg)](https://github.com/roryeckel/sector-ai/blob/master/LICENSE)

Sector AI is a Telegram bot that brings a chat model into your conversations. LangGraph orchestrates a single bounded agent over LangChain models. It can choose SVG, HTML, generated files, stickers, poll (including quiz mode), reaction, poll closing, and explicitly configured MCP tools, while keeping the existing slash commands. Uploaded documents (PDF, DOCX and text-like files) join the conversation as extracted text. Stickers enter as metadata-only markers; an image-capable model can fetch one on demand to describe it.

## Backends

The bot runs on either of two backends. Both are first-class: streaming replies, photos, autoreply decisions, model switching and token counting all work the same.

- **Ollama** (default) — Ollama's native API.
- **OpenAI-compatible** — Chat Completions against any `/v1` endpoint: LM Studio, vLLM, llama.cpp, OpenRouter, OpenAI itself, or your own inference server.

No models are bundled. Point the bot at a server you already run and set `SECTOR_AI_DEFAULT_MODEL` to a model it serves. With a multimodal default model, photos are part of the conversation itself. With a text-only one, set `SECTOR_AI_DEFAULT_MODEL_VISION=false` and optionally `SECTOR_AI_VISION_MODEL` to have photos described; see [Photos](#photos).

### Ollama

Install [Ollama](https://ollama.com/download), then pull a model:

```sh
ollama pull <model>
```

`SECTOR_AI_LLM_PROVIDER` defaults to `ollama`, so nothing else needs enabling. Set `SECTOR_AI_DEFAULT_MODEL` to the model you pulled, or let an admin pick one at runtime with `/models`.

### OpenAI-compatible

Set the provider and point the bot at the server's `/v1` root:

```sh
SECTOR_AI_LLM_PROVIDER=openai
SECTOR_AI_OPENAI_BASE_URL=https://your-server.example/v1
SECTOR_AI_OPENAI_API_KEY=...
```

The URL must include `/v1`. Leave the key empty for a server that does not check one; the bot sends `dummy`. Use the server's own model names in `SECTOR_AI_DEFAULT_MODEL` (and `SECTOR_AI_VISION_MODEL`, if used), for example `vendor/model` on OpenRouter.

| Server | `SECTOR_AI_OPENAI_BASE_URL` |
| --- | --- |
| Ollama | `http://localhost:11434/v1` |
| LM Studio | `http://localhost:1234/v1` |
| vLLM | `http://localhost:8000/v1` |
| llama.cpp | `http://localhost:8080/v1` |
| OpenRouter | `https://openrouter.ai/api/v1` |
| OpenAI | `https://api.openai.com/v1` |

Ollama also has an OpenAI-compatible `/v1` route, so switching that server to the `openai` provider is only a URL and provider change.

### Context length

Context length is set on the server. For Ollama, use `OLLAMA_CONTEXT_LENGTH` in its environment or `PARAMETER num_ctx` in a Modelfile; for other servers use their equivalent, such as vLLM's `--max-model-len`.

The bot reads the window the server advertises, so `/tokens` can show a percentage and compaction knows when to run. It checks, in order: `SECTOR_AI_CONTEXT_LENGTH` when set above zero, then the model's own metadata (`/v1/models` `context_length` or `max_model_len`, Ollama's `/api/ps` or `/api/show`), then a conservative 8192. The lookup happens once per endpoint and model, not on every message.

### Context compaction

Instead of dropping the oldest messages at a fixed count, the bot keeps a running summary. When the next request would pass `SECTOR_AI_COMPACTION_THRESHOLD` of the context window, the oldest messages are folded into the summary and only the most recent `SECTOR_AI_COMPACTION_KEEP_MESSAGES` stay verbatim. The summary is sent as a second system message, so a custom system prompt keeps working.

Compaction uses the model server itself, so it works the same on every backend. OpenAI's native Responses compaction is not used: it returns an opaque item that is only valid on that API, and most compatible servers, including Ollama and most self-hosted ones, do not implement it.

If summarization fails, the oldest messages are dropped to fit the window instead and the bot keeps chatting; `SECTOR_AI_COMPACTION_MAX_MESSAGES` still bounds the history as a safety net. With a positive cap, the next answering turn compacts at 80% of it so messages are summarized before the cap can drop them. Set the cap to `0` to disable the message limit entirely and let the context window and compaction be the only guardrail; this requires compaction to stay enabled. A chat where the bot never answers does not run compaction, so with `0` its history grows until the next reply, and with a positive cap the safety cap remains the only passive bound. `/compact` (admin only) forces a compaction and reports the token change.

### Message formatting

Model replies are rendered with Telegram formatting: bold and italic, inline and fenced code with the language label, links, block quotes, spoilers, and list markers. Headings become bold or underlined text and tables become monospace blocks, because Telegram has no heading, list or table entities.

Rendering uses Telegram message entities rather than `parse_mode`, so nothing is escaped and a half-written reply cannot break delivery. If Telegram rejects a formatted update, the same text is sent without formatting and the rest of that reply stays plain; formatting is never allowed to cost a message. Set `SECTOR_AI_MARKDOWN=false` to send raw text.

Replies longer than Telegram's 4096-character limit are split across messages at line breaks, with entities continuing across the split.

### Outbound rate limits

Every outgoing chat request shares a small PTB `BaseRateLimiter` budget of about 30 requests per second. New messages and edits share one request per second per chat and 20 per minute per group or channel (groups and channels share a negative chat ID, so both receive the group quota); Telegram counts edits against the same limits as messages. Live drafts and typing actions have their own documented budget of 20 calls per five seconds and 40 per thirty seconds per peer. Deletes, reactions and other chat-scoped calls are only subject to the bot-wide budget. `getUpdates` and other chat-less calls are untouched.

A streaming reply in a private chat uses Telegram's native live draft (`sendMessageDraft`) and posts the final answer as a normal message; drafts are private-chat only. Groups keep edit streaming, paced at `SECTOR_AI_STREAMING_GROUP_MIN_INTERVAL_SEC` (default 4s, 15 previews per minute) so a long answer leaves room for the group's new-message quota. When drafts are disabled or unavailable, private edits are paced at `SECTOR_AI_STREAMING_PRIVATE_MIN_INTERVAL_SEC` (default 1s). The effective interval is the larger of `SECTOR_AI_STREAMING_INTERVAL_SEC` and the chat's floor. A preview that hits flood control is skipped until Telegram's window expires; the final delivery waits and retries instead of dropping the answer on the first flood. Continuation parts and other new messages wait for a free slot. Calls that already retry network and flood-control errors keep that behavior.

## Features

### Photos

Photos are ordinary messages in the conversation. They go through the same autoreply decision and agent turn as text, so a caption can ask for an SVG, a poll or a reaction, and later messages can refer back to the photo.

- **Native** (default): the photo is attached to its message and the default model sees the pixels on that turn and later ones. The bot uses the largest Telegram rendition up to `SECTOR_AI_IMAGE_MAX_SIDE`, downloads it once, and re-sends identical bytes, so a prefix-caching server can reuse the cached prompt.
- **Describe**: with `SECTOR_AI_DEFAULT_MODEL_VISION=false` and `SECTOR_AI_VISION_MODEL` set, the vision model describes each photo the first time a reply needs it. The description replaces the photo in the user's message, labelled as coming from that model.
- **Off**: with neither, the conversation records `[photo …: image input is unavailable for this model]` so the model knows a photo was sent.

An album is collected until no new photo has arrived for `SECTOR_AI_ALBUM_WAIT` seconds, capped at 10 seconds after its first photo (or the configured wait, if longer), and answered as one turn. Photos count toward the context window by size (about one token per `SECTOR_AI_IMAGE_PATCH_PX`² pixels), so compaction triggers on time. Media the bot has not answered yet is kept ahead of the ordinary image-history budget, so another member's photo does not evict a pending question while it is still in history. The hard request cap can still reduce it to a still, or detach it when even one frame does not fit. Compaction keeps `SECTOR_AI_IMAGE_HISTORY_LIMIT` earlier photos attached and turns older ones into text markers; the model's earlier replies about them remain. `SECTOR_AI_IMAGE_MAX_ATTACHED` caps attached photos per request, for servers that limit images per prompt. If the hard cap forces a pending GIF down, it keeps one still frame when the cap has room. An explicitly replied-to media message is re-inserted after compaction, subject to the same image and token limits. Tools that call a model themselves, such as `generate_svg`, see the photo marker and the conversation, not the pixels.

### GIFs

Telegram delivers a GIF as a short MP4 (plus a still thumbnail); the model reads images, not video. The bot samples up to `SECTOR_AI_GIF_MAX_FRAMES` frames (8) at `SECTOR_AI_GIF_FRAME_SIDE` pixels (480) with ffmpeg and attaches them exactly like photos, so later turns and follow-ups can refer to the motion. One marker describes the whole GIF and makes the sampling explicit, e.g. `[gif, 480x270, 2s, 8 sampled frames, evenly spaced ~0.25s apart: attached; motion between frames not seen]`. The count is the number of attached samples, not the animation's original frame count; a trimmed request says how many of the samples it kept.

Sampling requires ffmpeg (`SECTOR_AI_FFMPEG_PATH`, or `ffmpeg` on `PATH`). Without it, or for a file over `SECTOR_AI_GIF_MAX_BYTES`, a failed download, an empty download or a decode timeout, the thumbnail is kept as one still and the marker says `still preview only`; `SECTOR_AI_GIF_MAX_FRAMES=0` selects still-only deliberately. Frames count individually toward the image history and request caps. A GIF document (`image/gif`) is handled the same way. Video messages are not sampled. Media downloads (photos and GIFs alike) are bounded per loader call — two minutes each — so a stalled download records the remaining media as failed (one record per message) instead of holding the conversation lock.

### Stickers

Stickers join the conversation as cheap metadata, not as downloaded artwork. A sticker-only message goes through the same autoreply decision and agent turn as text, and its marker stays in history and compaction, for example `[sticker: 😹, set "CatPack", static, 512x512, #a1b2c3d4]`. Static, animated and video stickers are named, along with whatever emoji, set and dimensions Telegram reported; missing fields are omitted rather than invented. The trailing tag is a short hash of Telegram's unique file ID: many packs give every sticker the same emoji and size, so only the tag tells two stickers apart. A replied sticker is marked in the reply metadata with its emoji and set, and the internal record retains its file ID, so a follow-up can send or describe that exact sticker. No artwork is downloaded unless the model explicitly asks for a description.

`send_sticker` re-sends a sticker this conversation already saw, selected by its Telegram message ID. It takes no file ID from the model, refuses a sticker from another chat, and records a receipt with the source message, file ID, emoji, set and format. `generate_sticker` asks the existing SVG generator for one centered subject with thick outlines, flat colors, a transparent background and no text, then encodes the result as a 512 px static sticker under 512 KB and sends it. Rendering or encoding failures happen before any Telegram send, so nothing is delivered. A delivered sticker receipt says it is already visible and must not be repeated; an uncertain send is never retried automatically.

When the configured model can read images (native vision, or `SECTOR_AI_VISION_MODEL` in describe mode), the model can call `describe_sticker(message_id)` to inspect a sticker already seen here. Only the requested sticker is downloaded. Static stickers become a 512 px JPEG; video stickers are sampled into evenly spaced frames exactly like GIFs, using the `SECTOR_AI_GIF_*` caps and ffmpeg; animated TGS stickers are Lottie JSON, not video, so the bot uses Telegram's still preview and says the motion was not decoded. The result is a description from the vision path, not direct pixels in the main conversation. The tool is not offered when image input is off, and static/still downloads are capped at 2 MB. The sticker prompt is configurable with `SECTOR_AI_SYSTEM_PROMPTS__STICKER_VISION`.

### Documents

PDF, DOCX and text-like files (plain text, Markdown, source code, CSV/TSV, JSON) join the conversation as extracted text. The bot downloads the file, extracts its text, and stores a record beside the message; the marker describes the file and the extracted text follows the caption in the prompt:

```
[telegram {...}]
[document: report.pdf, 12 pages]
testuser: Summarize section 2.
[extracted text from report.pdf #3f9c2a7b1d4e6f80]
...extracted text...
[end of extracted text from report.pdf #3f9c2a7b1d4e6f80]
```

The fence lines carry a random tag drawn when the file is extracted, and only the closing line with the matching tag ends the text, so a file cannot close its own fence: it would have to guess the tag. As defense in depth, a line in the text that imitates one of the bot's own markers — its first visible character an opening bracket (look-alikes and invisible prefixes included) followed by a marker word such as `telegram`, `document`, `photo`, `gif`, `sticker`, `voice` or `end of extracted text` and then more text, as every real marker has (case, fullwidth letters, invisible padding and dash look-alikes included) — has that leading bracket turned into a parenthesis, so the text cannot pose as the `[telegram ...]` envelope or a media marker either. Ordinary bracketed lines (TOML tables such as `[telegram]` or `[tool.ruff]`, JSON arrays, Markdown links such as `[Document](url)`, log levels) are left exactly as they are; a line like `[Photo: Reuters]` that has a real marker's shape is the exception.

The allowlist covers `.pdf` (a real PDF reader must be able to open it), DOCX (verified as a ZIP with a `word/document.xml` body), and text-like extensions — `.txt`, `.log`, `.md`, `.csv`, `.tsv`, `.json`, code and configuration files; a recognized extension decides, and only a missing or unrecognized one falls back to the MIME type (`text/*` and a few structured types). Anything else is recorded with a `[document: archive.zip: file type not supported]` marker, so the model knows a file was sent and can say so; no download is attempted for it.

Caps: `SECTOR_AI_DOCUMENT_MAX_BYTES` (20 MB) on the download, `SECTOR_AI_DOCUMENT_MAX_PAGES` (50) on PDF pages, and `SECTOR_AI_DOCUMENT_MAX_CHARS` (20,000) on extracted characters; extraction stops at the character cap instead of materializing the whole file just to cut it, separators count against the cap, and the marker states when a file was cut short (`first 50 extracted`, or for a text file whose full length is known `[document: notes.md, 95,000 characters, first 20,000 extracted]`; a PDF or DOCX cut by the budget reports `first 20,000 characters`, since the budget counts raw characters before normalization). A PDF with no text layer is marked `no extractable text (possibly a scanned image)` — there is no OCR. A PDF's cost is not bounded by its size (a file under 1 MB can make the parser use gigabytes), so PDFs are parsed in a separate process that is killed after 30 seconds and capped at 1 GB of memory (a Job Object on Windows, `RLIMIT_AS` elsewhere, never above a lower limit the host already sets; macOS does not enforce `RLIMIT_AS`, so there only the time limits apply). The process gets a minimal environment (no bot token or API keys; interpreter variables such as `PYTHONHOME` and `LD_LIBRARY_PATH` are kept) and does not import from the working directory; a worker that cannot start is reported as `the PDF reader could not start` and logged as an error. Its answer is size-capped, at most two run at once, and a file that exceeds the limits is marked `could not be read (the PDF is too complex to read)`. A frozen/packaged build cannot launch the worker and reports PDFs as unreadable. DOCX extraction uses the standard library and parses the body as a stream — no element tree, an element ceiling against no-text element bombs (truncation, not failure, once text was read), a nesting-depth limit, every buffer trimmed to the character budget — and rejects hostile archives (an oversized or ZIP64 central directory, checked by byte size as well as entry count before `zipfile` walks it; oversized bodies; any compression other than stored or deflate, which could expand unboundedly inside one read) plus DTDs — any `DOCTYPE` or entity declaration, in any encoding — at the parser level, so entity expansion cannot allocate memory. Text files must decode as UTF-8 (a BOM may select UTF-8 or UTF-16); control bytes and other binary content are rejected rather than decoded to garbage. Every incoming document is downloaded and extracted during ingestion, even in group chats the bot stays silent in; the caps and the PDF process limits bound the per-file cost. The original bytes are not stored: extraction is one-way. Extracted text is treated as data, not instructions, in every prompt.

### Voice and audio

Voice notes (`message.voice`) and audio files (`message.audio`) are transcribed to text so they join the conversation like any other message. Transcription uses a **separate OpenAI-compatible endpoint, configured independently of the main chat LLM**: `SECTOR_AI_TRANSCRIPTION_BASE_URL`, `SECTOR_AI_TRANSCRIPTION_API_KEY` and `SECTOR_AI_TRANSCRIPTION_MODEL`. The main `SECTOR_AI_OPENAI_*` settings and model are never reused, and an empty base URL disables transcription entirely — the message is then recorded with a `[voice, 4s: transcription unavailable (…)]` marker so the bot still knows something was sent and can acknowledge it.

The bot POSTs the original bytes to `{base_url}/audio/transcriptions` (`/v1` is added when the base URL omits it) with multipart `file` and `model` fields through the OpenAI SDK, and reads the standard `{"text": …}` response. The API key is optional: an unauthenticated endpoint (a local whisper server) works, and no `Authorization` header is sent at all. Telegram voice notes are OGG/Opus and are sent as `voice.ogg`; audio files keep their own filename and MIME type. Clips longer than `SECTOR_AI_TRANSCRIPTION_MAX_DURATION` (10 minutes) or larger than `SECTOR_AI_TRANSCRIPTION_MAX_BYTES` (20 MB) are recorded without a transcript. If the endpoint answers 415 or 422 (the container was not understood) and ffmpeg is available (`SECTOR_AI_FFMPEG_PATH`, shared with the GIF sampler), the audio is re-encoded as WAV once and tried again — any other 4xx, auth failures included, is final; ffmpeg is never required. The SDK's own retries are disabled (`max_retries=0`) and replaced by ours: one retry on network errors, 429 (honoring a `Retry-After` of up to 30 seconds) and 5xx. The whole transcription is bounded by roughly twice `SECTOR_AI_TRANSCRIPTION_TIMEOUT`, so a slow endpoint cannot stall the conversation. Transcript text is logged like any other message content (the success line and the ingestion journal carry the words, as logged prompts do); the API key never appears in logs (the endpoint URL itself can appear in the HTTP client's request lines, as it does for the main LLM), and errors never name the endpoint or key. The transcription happens inside the message's turn, which is registered on arrival, so a text sent right after a voice note cannot overtake it. Voice notes also take part in the engagement decision: a voice-only message is answered when autoreply decides it should be, and the decision sees the transcript (the one exception is the pre-ingest debounce relevance check, which sees only the marker, as it does for an undownloaded photo).

### Voice replies

Outbound speech is the reverse direction and uses its **own** OpenAI-compatible text-to-speech endpoint, configured with `SECTOR_AI_SPEECH_*`. It is independent of the main chat LLM and of transcription: `SECTOR_AI_OPENAI_*` and `SECTOR_AI_TRANSCRIPTION_*` are never reused. An empty `SECTOR_AI_SPEECH_BASE_URL` disables speech: the `send_voice` tool is not offered to the model, and `/speak` answers with a configuration hint.

The bot POSTs JSON to `{base_url}/audio/speech` (`/v1` is added when missing) with `model`, `input`, `voice` and `response_format`. `instructions` is included only when `SECTOR_AI_SPEECH_INSTRUCTIONS` is set, so other compatible servers do not receive an unknown field they may reject. The API key is optional: with no key, no `Authorization` header is sent, so an unauthenticated local server (for example Kokoro or another OpenAI-compatible TTS server) works. Responses are capped at 20 MB. The first bytes are checked for a real container (Ogg, MP3, M4A, WAV, FLAC or WebM); a generic content type with no recognizable container is rejected rather than sent as the configured format.

`opus` (OGG/Opus, Telegram's native voice-note format), `mp3` and `m4a` are sent directly with `sendVoice`. WebM and other response formats are converted to OGG/Opus with ffmpeg when it is available (`SECTOR_AI_FFMPEG_PATH`, shared with the GIF sampler). If ffmpeg is missing or conversion fails, the bytes are delivered as an audio file rather than losing the reply; headerless PCM is wrapped in a playable WAV container first. The model can call `send_voice` when speech is enabled, and `/speak <text>` does the same without a model call, even when agent tools are disabled or autoreply is off. A delivery receipt records the message ID, model, voice, format, duration when Telegram reports one, and the spoken text; it says the audio was delivered, so the model must not duplicate it as text. The tool is only exposed when the endpoint is configured, and a media send whose reply target was deleted is retried without the reply.

| Variable | Default | Purpose |
| --- | --- | --- |
| `SECTOR_AI_SPEECH_BASE_URL` | *empty* | OpenAI-compatible text-to-speech endpoint, independent of the main LLM and transcription (`/v1` optional). Empty disables speech. |
| `SECTOR_AI_SPEECH_API_KEY` | *empty* | Key for the speech endpoint. Empty sends no `Authorization` header, for an unauthenticated local server. |
| `SECTOR_AI_SPEECH_MODEL` | *empty* | TTS model sent with each request, e.g. `tts-1`, `gpt-4o-mini-tts` or `kokoro`. Required when the base URL is set. |
| `SECTOR_AI_SPEECH_VOICE` | `alloy` | Provider-specific voice name, e.g. `alloy`, `nova` or `af_heart`. |
| `SECTOR_AI_SPEECH_FORMAT` | `opus` | Requested response format: `opus`, `mp3`, `aac`, `flac`, `wav` or `pcm`. |
| `SECTOR_AI_SPEECH_TIMEOUT` | `60.0` | Whole-request budget in seconds, retries included. |
| `SECTOR_AI_SPEECH_MAX_CHARS` | `2000` | Longest text one request may speak (max 4096). |
| `SECTOR_AI_SPEECH_INSTRUCTIONS` | *empty* | Optional style instructions for models that support them; omitted entirely when empty. |

One bounded retry follows a network error, a 429 (honoring a `Retry-After` of up to 30 seconds) and a 5xx; other 4xx answers are final. The whole request, including the retry wait, is bounded by `SECTOR_AI_SPEECH_TIMEOUT`; the `send_voice` tool's own timeout includes room for synthesis, conversion and upload. Errors never name the endpoint or key, although the HTTP client may log request URLs at INFO as it does for transcription.

### Agent and tool-aware history

Ask naturally for a drawing, page, poll, quiz, reaction, sticker, a description of a sticker, a generated file, a spoken reply, or a different set of reply buttons; a tool-capable model can choose the appropriate capability itself. `send_file` delivers generated CSV, TSV, JSON, Markdown or plain-text files as documents: the model provides the complete file content, the filename must use an allowed extension, JSON is validated before sending, and the delivery receipt tells the model the file is already visible so it does not repeat the contents. `send_sticker` re-sends a sticker already seen in the conversation, `generate_sticker` creates a static sticker through the SVG pipeline, `describe_sticker` describes one on demand, and `offer_actions` chooses the reply buttons described below. `send_voice` speaks text through the separate speech endpoint and delivers it as a voice note (or an audio file when conversion is unavailable); the receipt says the audio is delivered, so the model does not repeat the words. There is no outbound PDF: PDFs need a layout engine, and `generate_html` already produces a printable page. `/svg`, `/html`, `/poll`, `/quiz`, `/topic`, and `/speak` explicitly select the generation capabilities or speak directly, `/stoppoll` closes a poll directly, and all of them work even with autoreply disabled or a model that cannot call tools.

Generated content and reaction receipts enter the conversation history: exact poll questions/options (including quiz answer keys), SVG source, HTML source, reaction emoji and target, and delivery outcomes. Follow-up messages can refer to those outputs, including outputs requested through commands. Other content commands also record their requests and replies. History is isolated by chat and forum topic, compacted as it fills, and kept in process memory only. Long replies, including continuation chunks, stay in the originating forum topic.

The model also receives current UTC time, observed chat/topic labels, message timestamps and sender identities, and explicit reply targets with short excerpts. Assistant messages are shown without their own internal `[telegram ...]` envelope, and any leading envelope is stripped before delivery, including during streaming. Joins/leaves, pins, chat-title changes, and forum-topic changes enter history as observed events without triggering replies on their own. The tool-free autoreply decision uses bounded recent history and the existing summary instead of judging only the latest text. It budgets the raw incoming text/caption before optional metadata, so an oversized sender label or reply excerpt cannot hide the actual question.

Message edits update retained text and record a correction without rerunning commands or tools. Final totals for bot-created polls return to the chat/topic where the poll was posted: the first closed snapshot for a poll is kept and later closed updates for the same poll are ignored, and a poll whose close time has passed can no longer be closed with `/stoppoll`. The bot can set one standard reaction on the current or a past message. In chats where it is an administrator, it also records user reaction changes — including removals, custom emoji and paid reactions — as silent context events; anonymous reaction counts are recorded as evolving aggregate totals. Telegram never reports reactions set by bots. Reaction observation can be disabled globally; Telegram still decides delivery per chat. Reaction events are kept only when the target message can be routed to the conversation that saw it; routing uses a bounded route map and retained message history, is process-local, and is dropped for messages with neither. Bot membership and permission changes are shared chat-wide context, never authorization to use additional tools. These events stay silent until a later conversation turn uses them.

Tool calls, iterations, execution time, and output size are bounded. An uncertain side effect stops further tool execution for that turn; Telegram polls and artifacts are not blindly resent. Reactions are retried once on a network failure because re-setting one is idempotent. If a run is interrupted, delivery uncertainty is attached only to the tool call that was executing, and unstarted calls are marked not executed. Set `SECTOR_AI_AGENT_TOOLS_ENABLED=false` to retain plain chat and explicit commands.

Prompt assembly keeps static instructions and retained history before the changing UTC/chat snapshot, so a new message does not invalidate the reusable prefix. Recognized OpenAI and OpenRouter endpoints receive request-local cache affinity; self-hosted compatible servers keep their own prefix cache and are never sent vendor-only fields. `/usage` reports token and cache counters by workload. See [prompt caching](docs/agent.md#prompt-caching-and-usage).

MCP is opt-in through a separate JSON file, with explicit tool allowlists and optional chat restrictions. See [agent configuration and behavior](docs/agent.md) and [`mcp.example.json`](mcp.example.json).

This project uses the `python-telegram-bot` library, with various command handlers and message handlers to manage different interactions. At startup the bot also registers its command menu with Telegram: everyone sees the public commands, and each numeric ID in `SECTOR_AI_ADMIN_USER_IDS` sees the admin commands in their private chat once Telegram knows that chat. The same pass sets the bot's description and short description, and resets the menu button to the command list. A username-only admin, or an admin who has not started the bot yet, gets the admin menu after their first private `/start` or `/help`, because the bot learns their numeric ID from that update. A failed profile update is logged without stopping polling; the next restart retries it, and a failed admin menu is repaired on that admin's next private `/start` or `/help`.

### Reply buttons

Agent text replies carry no buttons unless the model asks for them. A tool-capable model calls `offer_actions` before or alongside its reply to stage one to four buttons, each with a label chosen for the conversation and a prompt saying what pressing it should ask for; a button whose action is `delete` removes the reply instead and is always labelled **Delete**. Rows are balanced by default to fit the labels' approximate width, and a button may set `row` (1–4) to choose its line; buttons without a row follow the named rows. A delete button sits on its own last row unless the model groups it. The tool never sends a message itself, and `SECTOR_AI_REPLY_BUTTONS=false` removes the tool and all buttons. Button labels are capped at 30 characters and prompts at 500; prompts are single-line, and URL buttons are not supported.

Callback data is a random token plus an action index, never a chat or prompt. The process-local registry expires entries after `SECTOR_AI_INTERACTION_TTL_SEC` (default one day, capped at two days because Telegram turns older callback messages into inaccessible placeholders) and evicts the oldest at `SECTOR_AI_INTERACTION_MAX` (default 512). A click is answered before any slow work, checked against the stored chat, topic and message, generation-checked against `/clear`, and deduplicated while it runs. Presses are rate-limited per user and chat by `SECTOR_AI_INTERACTION_COOLDOWN_SEC` (default 2 seconds). A follow-up button runs a real agent turn with tools and streaming, doing what that button's prompt asks. The clicked row is removed before the turn runs, so a button cannot start an endless chain. The press is recorded as an observed, untrusted event, while its instruction lives only in that turn's system prompt. **Delete** is limited to the person who asked, removes every part of a split reply, and records the deletion as an observed event. The row is attached only after streaming ends, on the last delivered part; a turn that sends no text attaches nothing.

Below is a summary of each command:

### Start (`/start`)
- **Description**: Shows the command reference. In a private chat it includes the admin commands when the sender is an admin.
- **Usage**: `/start`

### Help (`/help`)
- **Description**: Shows the same command reference as `/start`, with the same private-chat admin section.
- **Usage**: `/help`

### Generate Response (`/chat`)
- **Description**: Initiates or continues a chat interaction with the user, using AI to generate responses based on the context of the conversation.
- **Usage**: `/chat [text]` (where `[text]` is the user's input)

### Summarize Chat Messages (`/summarize`)
- **Description**: Provides a summary of the current chat messages in context, potentially generated by the AI to quickly grasp the conversation’s essence.
- **Usage**: `/summarize`

### Generate Emojis Based on Prompt (`/emoji`)
- **Description**: Creates emojis based on user input, or from the recent conversation when no prompt is given. Recent history is bounded to the context window, oldest messages dropped first.
- **Usage**: `/emoji [prompt]` (where `[prompt]` is a description of what kind of emoji you want; leave it out to summarize the current conversation)

### Generate a Poll Based on Question or Prompt (`/poll`)
- **Description**: Creates a poll with multiple options based on user input, useful for gathering feedback. The model decides the poll shape from the prompt; use `/quiz` to force quiz mode with a marked answer key.
- **Usage**: `/poll [question]` (where `[question]` is the description of the poll)

### Create a Quiz (`/quiz`)
- **Description**: Creates a quiz-mode poll: the model marks the correct option(s), and voters see whether they were right. It can also include an explanation, a description, shuffled options, multiple correct answers, and an open period or close date when the prompt asks for them.
- **Usage**: `/quiz <question>` (where `<question>` describes the quiz)

### Generate a Poll with Chat Related Topics (`/topic`)
- **Description**: Creates a poll where users can vote on topics discussed recently in the chat context.
- **Usage**: `/topic`

### Close a Poll (`/stoppoll`)
- **Description**: Closes the newest open poll the bot posted in this chat or forum topic, or a specific poll message by ID. The final totals are recorded in the conversation.
- **Usage**: `/stoppoll [message_id]`

### Return "True" or "False" Based on Prompt (`/decide`)
- **Description**: Uses AI to decide between two possible outcomes based on user input.
- **Usage**: `/decide [prompt]` (where `[prompt]` is the question you want decided by the bot)

### Generate a Code Block Based on Specification (`/code`)
- **Description**: Generates a code snippet according to specific requirements or inputs provided by the user.
- **Usage**: `/code [specification]` (where `[specification]` describes what kind of code to generate, e.g., Python function)

### Generate Fake Website Based on Specification (`/html`)
- **Description**: Renders a mock HTML website based on given specifications or details from the user.
- **Usage**: `/html [specification]` (where `[specification]` includes layout and content requirements)
- **Note**: The page is sent as `Website.html` without restrictions, so it may contain scripts or forms requested by any chat member. Open it like any other attachment from the chat.

### Generate Horrible SVG Image Based on Description (`/svg`)
- **Description**: Creates an SVG graphic according to detailed descriptions provided by users, often with humorous or nonsensical results.
- **Usage**: `/svg [description]` (where `[description]` can be anything from a simple shape to a complex scene)

### Speak a Reply as a Voice Note (`/speak`)
- **Description**: Synthesizes the given text through the separate speech endpoint and sends it as a Telegram voice note. Works without a model call, even when agent tools are disabled or autoreply is off. If ffmpeg is unavailable for a non-native format, the audio is sent as an audio file instead. Requires `SECTOR_AI_SPEECH_BASE_URL` and `SECTOR_AI_SPEECH_MODEL`.
- **Usage**: `/speak <text>` (where `<text>` is what the voice note should say)

### Get the Current Context Size (`/tokens`) (Admin Only)
- **Description**: Counts the system prompt and current chat history with the model server's tokenizer when available, so messages that have not been processed yet are included. On an OpenAI-compatible server it first uses OpenAI's free `/responses/input_tokens` endpoint, which counts the Responses API input and can differ slightly from a Chat Completions request. If that endpoint is missing, it falls back to a one-token probe for the exact chat count; on a paid endpoint that probe sends the whole prompt as a normal request. The result is cached until the context or model changes. If the server reports no count, the reply is marked as an estimate. When the server also reports its context window, the reply shows the count as a percentage of it. Ollama can truncate a prompt that exceeds the server's context window, so the reported number is then a lower bound.
- **Usage**: `/tokens`

### Inspect Model Usage (`/usage`) (Admin Only)
- **Description**: Shows the model, provider host, and per-workload request, input, output, cache-read, cache-write and cache-hit counters since the process started. Counters come from the model server's usage report; streaming counters require `SECTOR_AI_STREAM_USAGE=true` on servers that support `stream_options`. Prompt text, tool arguments and credentials are never included.
- **Usage**: `/usage`

### Compact the Context (`/compact`) (Admin Only)
- **Description**: Folds the older messages into the running summary immediately, keeps the most recent messages verbatim, and reports the token count before and after. Normally runs on its own before a reply; this command is for testing or for shrinking the context on demand.
- **Usage**: `/compact`

### Toggle Automatic Replies (`/autoreply`)
- **Description**: Enables or disables automatic replies triggered by the LLM decision. When enabled, the bot decides whether to respond to each message, photos and stickers included.
- **Usage**: `/autoreply` to toggle the feature

### Reset Chat Context (`/clear`)
- **Description**: Resets the context of the conversation, effectively starting a new chat from scratch.
- **Usage**: `/clear`

### Set System Prompt (Admin Only) (`/system`)
- **Description**: Allows administrators to set or modify the system prompt that guides the behavior of the AI within the chat context.
- **Usage**: `/system [prompt]` where `[prompt]` is the new system message you want the bot to follow.

### Generate System Prompt (Admin Only) (`/characterize`)
- **Description**: Uses the model to write a system prompt from the requested persona, then replaces this chat's system prompt with it and clears the conversation history.
- **Usage**: `/characterize [details]` where `[details]` are a thing for the LLM to roleplay as.

### Set the Model Temperature (Admin Only) (`/temperature`)
- **Description**: Sets the model temperature for subsequent replies in every chat. Call it without a value to clear the setting and use the model's default.
- **Usage**: `/temperature [value]`

### Set the Model (Admin Only) (`/models`)
- **Description**: Lists available models in pages of 40 and switches the bot to the selected one. Use `/models 2` to open a later page directly.
- **Usage**: `/models [page]`

## Getting Started

### From PyPI

```sh
pip install sector-ai
```

Create a `.env` in the directory you will run from, or export the variables directly. The [Configuration](#configuration) table lists every setting; at minimum you need `TELEGRAM_BOT_TOKEN` and a reachable [backend](#backends).

```sh
sector-ai
```

`sector-ai` reads `.env` from the current directory. `python -m sector_ai` is equivalent.

### From a clone

1. **Prerequisites**: Python 3.11 or newer and one reachable [backend](#backends) — Ollama or any OpenAI-compatible server.
2. **Clone and install**:
    ```sh
    git clone https://github.com/roryeckel/sector-ai.git
    cd sector-ai
    pip install .
    ```
3. **Configure**: copy `.env.example` to `.env`, then set `TELEGRAM_BOT_TOKEN` and the backend and model values you need.
4. **Run**: `sector-ai`

Upgrading from 1.3.x: the `--config` flag and `config.json` are gone. Move the values you had changed into `.env`; `.env.example` lists every setting and its default.

## Docker

Images are published to the GitHub Container Registry for `linux/amd64` and `linux/arm64`. The bot makes no inbound connections, so no ports are exposed.

The example below reaches Ollama on the host. For an OpenAI-compatible server, add `-e SECTOR_AI_LLM_PROVIDER=openai -e SECTOR_AI_OPENAI_BASE_URL=http://host.docker.internal:11434/v1` (or the server's public `/v1` URL), plus `-e SECTOR_AI_OPENAI_API_KEY=...` if it checks one.

```sh
docker run -d --name sector-ai --restart unless-stopped \
  -e TELEGRAM_BOT_TOKEN=your-token \
  -e OLLAMA_URL=http://host.docker.internal:11434 \
  --add-host host.docker.internal:host-gateway \
  ghcr.io/roryeckel/sector-ai:latest
```

Or, from a clone, `compose.yaml` does the same:

```sh
cp .env.example .env   # set TELEGRAM_BOT_TOKEN and OLLAMA_URL
docker compose up -d
```

Inside the container, `localhost` is the container itself, so a server on the host needs `host.docker.internal` (Docker Desktop resolves it automatically; the `--add-host` flag or the `extra_hosts` entry in `compose.yaml` covers Linux). A remote OpenAI-compatible server needs no special host entry — set `SECTOR_AI_OPENAI_BASE_URL` to its public URL.

Image tags:

| Tag | Meaning |
| --- | --- |
| `latest` | latest published release, not a prerelease |
| `1.4.0` | exact release |
| `1.4` | latest patch of that minor |
| `edge` | latest commit on `master` |
| `sha-abc1234` | exact commit |

## Configuration

Bot settings come from environment variables, an optional `.env` file in the working directory, or the command line (which wins over both). MCP server definitions optionally live in a separate JSON file selected by `SECTOR_AI_MCP_CONFIG`; the old general-purpose `config.json` is not used.

| Variable | Default | Purpose |
| --- | --- | --- |
| `TELEGRAM_BOT_TOKEN` | *required* | Token from [@BotFather](https://t.me/BotFather). `SECTOR_AI_TELEGRAM_BOT_TOKEN` is also accepted. |
| `SECTOR_AI_LLM_PROVIDER` | `ollama` | Backend: `ollama` for the native API, or `openai` for any OpenAI-compatible endpoint. |
| `OLLAMA_URL` | `http://localhost:11434` | Ollama endpoint, used by the `ollama` provider. `SECTOR_AI_OLLAMA_URL` is also accepted. |
| `SECTOR_AI_OPENAI_BASE_URL` | `http://localhost:11434/v1` | Base URL for the `openai` provider; must include `/v1`. |
| `SECTOR_AI_OPENAI_API_KEY` | *empty* | Key for the `openai` provider. Empty sends `dummy`, which local servers ignore. |
| `SECTOR_AI_DEFAULT_MODEL` | `llama3.2-vision:11b-instruct-fp16` | Chat model at start-up. Set it to a model the backend serves. |
| `SECTOR_AI_DEFAULT_MODEL_VISION` | `true` | The default model reads images, so photos are sent inline. Set `false` for a text-only model. |
| `SECTOR_AI_VISION_MODEL` | *empty* | Only when `SECTOR_AI_DEFAULT_MODEL_VISION=false`: model that describes photos. Empty records a placeholder instead. |
| `SECTOR_AI_IMAGE_MAX_SIDE` | `1280` | Largest Telegram photo rendition to use, by longest side in pixels. |
| `SECTOR_AI_IMAGE_HISTORY_LIMIT` | `4` | Earlier photos kept attached after a compaction; the newest photo message stays whole when the request cap allows it. |
| `SECTOR_AI_IMAGE_MAX_ATTACHED` | `32` | Cap on attached photos per request (`0` for none, which requires compaction). Exceeding it detaches older answered photos first; pending GIFs keep a still frame when room remains. |
| `SECTOR_AI_IMAGE_PATCH_PX` | `28` | Pixels per image token used by the local token estimate. |
| `SECTOR_AI_GIF_MAX_FRAMES` | `8` | Frames sampled from a GIF (`0` keeps only the still thumbnail; max 32). |
| `SECTOR_AI_GIF_FRAME_SIDE` | `480` | Longest side of a sampled GIF frame in pixels. |
| `SECTOR_AI_GIF_MAX_BYTES` | `15728640` | Largest GIF clip downloaded for sampling; larger files use the thumbnail. |
| `SECTOR_AI_DOCUMENT_MAX_BYTES` | `20971520` | Largest inbound document downloaded (PDF, DOCX, text-like files). |
| `SECTOR_AI_DOCUMENT_MAX_PAGES` | `50` | PDF pages extracted per document; the marker says when it was cut short. |
| `SECTOR_AI_DOCUMENT_MAX_CHARS` | `20000` | Extracted characters kept per document. |
| `SECTOR_AI_SEND_FILE_MAX_CHARS` | `50000` | Largest file content the `send_file` tool accepts, in characters. |
| `SECTOR_AI_GIF_TIMEOUT` | `20.0` | Seconds allowed for ffmpeg to sample one GIF. |
| `SECTOR_AI_FFMPEG_PATH` | `ffmpeg` | ffmpeg executable or absolute path. Missing ffmpeg means still previews. |
| `SECTOR_AI_TRANSCRIPTION_BASE_URL` | *empty* | OpenAI-compatible endpoint for voice/audio transcription, independent of the main LLM (`/v1` optional). Empty disables transcription. |
| `SECTOR_AI_TRANSCRIPTION_API_KEY` | *empty* | Key for the transcription endpoint. Never the main LLM key. |
| `SECTOR_AI_TRANSCRIPTION_MODEL` | *empty* | Model name sent with each transcription request, e.g. `whisper-1`. |
| `SECTOR_AI_TRANSCRIPTION_TIMEOUT` | `60.0` | Seconds allowed for one transcription request. |
| `SECTOR_AI_TRANSCRIPTION_MAX_DURATION` | `600.0` | Longest voice/audio clip transcribed, in seconds. |
| `SECTOR_AI_TRANSCRIPTION_MAX_BYTES` | `20971520` | Largest file uploaded for transcription, in bytes. |
| `SECTOR_AI_SPEECH_BASE_URL` | *empty* | OpenAI-compatible text-to-speech endpoint for voice replies, independent of the main LLM and transcription (`/v1` optional). Empty disables speech. |
| `SECTOR_AI_SPEECH_API_KEY` | *empty* | Key for the speech endpoint. Empty sends no `Authorization` header, for an unauthenticated local server. |
| `SECTOR_AI_SPEECH_MODEL` | *empty* | TTS model, e.g. `tts-1`, `gpt-4o-mini-tts` or `kokoro`. Required when the base URL is set. |
| `SECTOR_AI_SPEECH_VOICE` | `alloy` | Provider-specific voice name. |
| `SECTOR_AI_SPEECH_FORMAT` | `opus` | Requested format: `opus`, `mp3`, `aac`, `flac`, `wav` or `pcm`. |
| `SECTOR_AI_SPEECH_TIMEOUT` | `60.0` | Whole speech request budget in seconds, retries included. |
| `SECTOR_AI_SPEECH_MAX_CHARS` | `2000` | Longest text one speech request may carry (max 4096). |
| `SECTOR_AI_SPEECH_INSTRUCTIONS` | *empty* | Optional style instructions for models that support them; omitted when empty. |
| `SECTOR_AI_ALBUM_WAIT` | `1.5` | Seconds to collect an album before answering it as one turn. |
| `SECTOR_AI_DEBOUNCE_MAX_RESTARTS` | `3` | How many times a newer relevant message, or an edit, may restart a turn that has not replied yet (`0` disables debouncing). |
| `SECTOR_AI_OBSERVE_REACTIONS` | `true` | Record user reaction changes as silent context events. Telegram delivers them only in chats where the bot is an administrator, and never for reactions set by bots. |
| `SECTOR_AI_OBSERVE_REACTION_COUNTS` | `true` | Record anonymous reaction-count snapshots as evolving per-message totals. Identical snapshots are ignored while retained; a trimmed totals event is restored. |
| `SECTOR_AI_ADMIN_USERNAMES` | `ex0dus` | Comma separated usernames (without `@`) allowed to use admin commands. A username-only admin gets the admin menu after their first private `/start` or `/help`; set `SECTOR_AI_ADMIN_USER_IDS` to try at startup too. |
| `SECTOR_AI_ADMIN_USER_IDS` | *empty* | Comma separated Telegram user IDs allowed to use admin commands, checked alongside the usernames. Use this for an admin whose account has no username, and to try giving an admin the menu at startup. Telegram only accepts the scope once that private chat is known, so an admin can still get it on their first private `/start` or `/help`. Removing an admin does not clear a menu Telegram has already stored. |
| `SECTOR_AI_DEFAULT_SVG_SIZE` | `250` | Base size for `/svg`; the rendered PNG is twice this. |
| `SECTOR_AI_STREAMING_CURSOR` | `🦙` | Cursor shown while a reply streams. |
| `SECTOR_AI_STREAMING_INTERVAL_SEC` | `0.7` | Preferred seconds between preview updates; the chat-type floor wins when larger. |
| `SECTOR_AI_STREAMING_CHUNK_SIZE` | `150` | Characters buffered before the first preview; later previews follow the interval. |
| `SECTOR_AI_STREAMING_DRAFTS` | `true` | Use Telegram live drafts for private-chat previews; `false` edits a normal message instead. |
| `SECTOR_AI_STREAMING_PRIVATE_MIN_INTERVAL_SEC` | `1.0` | Safety floor between private-chat preview edits. |
| `SECTOR_AI_STREAMING_GROUP_MIN_INTERVAL_SEC` | `4.0` | Safety floor between group and channel preview edits (15 per minute). |
| `SECTOR_AI_STREAMING_DRAFT_INTERVAL_SEC` | `2.0` | Minimum seconds between live-draft updates. |
| `SECTOR_AI_MARKDOWN` | `true` | Render model markdown as Telegram formatting. `false` sends raw text. |
| `SECTOR_AI_REPLY_BUTTONS` | `true` | Allow inline buttons under agent replies. The model decides when to offer them with `offer_actions`; `false` removes the tool and all buttons. |
| `SECTOR_AI_INTERACTION_TTL_SEC` | `86400` | Seconds a reply-button callback stays valid (`60`-`172800`; two days is Telegram's callback limit). |
| `SECTOR_AI_INTERACTION_MAX` | `512` | Maximum stored reply-button keyboards; the oldest is evicted first (`1`-`10000`). |
| `SECTOR_AI_INTERACTION_COOLDOWN_SEC` | `2.0` | Per-user, per-chat cooldown between button presses (`0`-`60`; `0` disables it). |
| `SECTOR_AI_LLM_TIMEOUT` | `200.0` | Request timeout in seconds. `SECTOR_AI_OLLAMA_TIMEOUT` is also accepted. |
| `SECTOR_AI_LLM_DISALLOWED_MODELS` | *empty* | Comma separated models hidden from `/models`. `SECTOR_AI_OLLAMA_DISALLOWED_MODELS` is also accepted. |
| `SECTOR_AI_LLM_HEADERS` | `{}` | JSON object of extra HTTP headers. `SECTOR_AI_OLLAMA_HEADERS` is also accepted. |
| `SECTOR_AI_PROMPT_CACHE_MODE` | `auto` | `auto` applies cache affinity only to recognized OpenAI/OpenRouter hosts. `off` disables it; `openai` and `openrouter` force a choice for an OpenAI-compatible provider. |
| `SECTOR_AI_PROMPT_CACHE_KEY_PREFIX` | `sector-ai` | Stable prefix for request-local cache/session keys. Chat and forum topic IDs are appended. |
| `SECTOR_AI_PROMPT_CACHE_RETENTION` | *empty* | OpenAI only, models before GPT-5.6: `in_memory` or `24h`. If a TTL is also set, the TTL wins and a startup warning says so. |
| `SECTOR_AI_PROMPT_CACHE_TTL` | *empty* | OpenAI (GPT-5.6+): `30m` for `prompt_cache_options`. OpenRouter: `1h` for Anthropic-style automatic caching. |
| `SECTOR_AI_STREAM_USAGE` | `false` | Ask OpenAI-compatible servers to include usage in stream chunks. Leave off for older local servers that reject `stream_options`. |
| `SECTOR_AI_AGENT_TOOLS_ENABLED` | `true` | Let a tool-capable chat model select tools autonomously. Explicit commands remain available when false. |
| `SECTOR_AI_AUTOREPLY_HISTORY_MESSAGES` | `8` | Maximum recent history messages supplied to the tool-free engagement decision. |
| `SECTOR_AI_AUTOREPLY_CONTEXT_TOKENS` | `1536` | Conservative token budget for the entire engagement prompt, further limited by the model window. |
| `SECTOR_AI_AGENT_MAX_TOOL_CALLS` | `6` | Maximum tool executions per turn. |
| `SECTOR_AI_AGENT_MAX_ITERATIONS` | `8` | Maximum autonomous model iterations per turn. |
| `SECTOR_AI_AGENT_TIMEOUT` | `240` | Overall agent turn timeout in seconds, excluding time waiting for the conversation lock. |
| `SECTOR_AI_TOOL_TIMEOUT` | `90` | Built-in capability timeout in seconds. |
| `SECTOR_AI_TOOL_RESULT_MAX_CHARS` | `16000` | Maximum history result size. Oversized external results are explicitly marked truncated; generated source is limited to half this size. |
| `SECTOR_AI_MCP_CONFIG` | *empty* | Optional MCP-only JSON configuration file. |
| `SECTOR_AI_CONTEXT_LENGTH` | `0` | Context window in tokens. `0` detects it from the server and falls back to 8192. |
| `SECTOR_AI_COMPACTION_ENABLED` | `true` | Fold old messages into a summary instead of dropping them. |
| `SECTOR_AI_COMPACTION_THRESHOLD` | `0.75` | Share of the context window that triggers a compaction. |
| `SECTOR_AI_COMPACTION_KEEP_MESSAGES` | `8` | Recent messages kept verbatim after a compaction. |
| `SECTOR_AI_COMPACTION_MAX_MESSAGES` | `500` | Safety cap used when compaction is off or fails. A positive value compacts at 80% on answering turns; `0` disables the cap and requires compaction enabled. |
| `SECTOR_AI_COMPACTION_SUMMARY_MAX_CHARS` | `4000` | Maximum summary length; longer summaries are truncated. |
| `SECTOR_AI_SYSTEM_PROMPTS__<NAME>` | built-in | Override one system prompt, e.g. `SECTOR_AI_SYSTEM_PROMPTS__SVG`. |
| `SECTOR_AI_LOG_LEVEL` | `INFO` | `CRITICAL`, `ERROR`, `WARNING`, `INFO` or `DEBUG`. |

Context length is detected from the server when possible; see [Context length](#context-length) and [Context compaction](#context-compaction).

**Upgrading:** `SECTOR_AI_OLLAMA_CONTEXT_LENGTH` is no longer read. Remove it and configure the context length on the Ollama server or in a Modelfile.

The flags worth changing per run are also on the command line: `--model`, `--vision-model`, `--provider`, `--ollama-url`, `--openai-url`, `--admin` and `--admin-id` (both repeatable), `--log-level` and `--version`. Secrets are intentionally environment-only, so a bot token or API key never lands in shell history or `ps` output.

## Contributions Welcome
