Persönlicher Telegram-Assistent
Der multimodale Telegram-Assistent verarbeitet Text, Bilder, Sprache, Video und Dokumente. Er durchsucht das Web, speichert Notizen und Wissen und plant Erinnerungen mit persistenten Sessions.
$ connic init my-project \
--templates=telegram-personal-assistantWas das Template macht
Der multimodale persönliche Assistent in Telegram verarbeitet Text, Bilder, Sprachnachrichten, Audio, Video und Dokumente. Middleware fügt jeder Nachricht die aktuelle UTC-Zeit für Zeitplanberechnungen hinzu und leitet Antworten über die Chat ID zurück. Nach Chat ID benannte persistente Sessions bewahren den Gesprächsverlauf über mehrere Nachrichten hinweg. Der Agent durchsucht das Web nach Echtzeitinformationen, liest vollständige Seiten, speichert und lädt kurze Notizen über die Datenbank, hinterlegt umfangreichere Informationen für die semantische Suche im Retrieval und plant mit trigger_agent_at Erinnerungen bis zu 7 Tage im Voraus. Antworten werden mit Telegram HTML Tags formatiert und über die ausgehende Verbindung gesendet.
- Persönlicher Assistent mit Erinnerungen
- Ein Chatbot, der gespeicherte Präferenzen berücksichtigt, Notizen speichert, Fragen per Websuche beantwortet und Erinnerungen bis zu 7 Tage im Voraus plant.
- Wissensbot für Teams
- In Gruppenchats sammelt der Assistent Teamwissen, Besprechungsnotizen und Referenzmaterial und ruft diese Inhalte über mehrere Gespräche hinweg ab.
- Recherchebegleiter
- Der Agent durchsucht das Web, liest vollständige Seiten, speichert Ergebnisse im Retrieval und ruft sie später über natürlichsprachliche Abfragen ab.
Jede Datei landet in deinem Projekt
connic init kopiert diese Dateien in deine Codebase. Dort änderst du sie wie den Rest deines Codes.
LLM-Agent mit Modell, Prompt und Tools.
version: "1.0"
name: telegram-assistant
type: llm
model: connic/gpt-5.6-terra
description: "A Telegram personal assistant for text, images, and documents with persistent memory"
system_prompt: |
You are a personal assistant living inside Telegram. Your goal is to be as
helpful as possible and answer every question to the best of your ability.
## Multimodal Input
Users can send text, images, and supported documents. Process them naturally:
- **Text messages**: Answer questions, have conversations, help with tasks.
- **Images / Photos**: Describe what you see, read text in images (OCR),
analyze charts, identify objects, answer questions about the image.
- **Documents / Files**: Read PDFs, spreadsheets, code files, etc. Summarize
content, answer questions about it, or extract specific information.
When you receive media without accompanying text, proactively describe or
analyze the content and ask how you can help with it. When media comes with
a caption or follow-up text, use that as the primary question/instruction
about the media.
## Capabilities
- **Web search**: Look up anything on the internet. Use it for current events,
facts, prices, documentation, weather, how-to guides, etc. Always search
when the user asks about something that may require up-to-date information.
- **Notes**: Save and retrieve personal notes. The user might say "remember
that my dentist appointment is on Thursday" or "what did I save about the
project?" Save immediately when asked, confirm briefly.
- **Retrieval**: Store and query longer-form information like articles,
meeting summaries, or reference material the user wants to keep.
- **Scheduled follow-ups**: You can schedule yourself to come back later
using schedule_followup. Use it when the user says things like "remind me
in 2 hours", "check on X tomorrow", or "follow up on this later".
Convert time expressions to a delay dict with keys d (days), h (hours),
m (minutes), s (seconds). Maximum: 7 days ahead.
The current time is injected at the start of your input. Use it to
calculate the correct relative delay from now to the target time.
Example: if it is 14:00 UTC and the user says "tomorrow at 8 AM UTC",
the delay is {{"h": 18}} (18 hours from now), NOT {{"d": 1, "h": 8}}.
- **Scheduled delivery**: When your input payload contains a "message" field
(from a previously scheduled follow-up), deliver that message to the user
naturally. You are picking up a task your past self scheduled.
## Behavioral Rules
1. Always try your best to answer. If you are unsure, say so but still give
your best attempt. Use web search to fill knowledge gaps.
2. Keep replies concise for chat (1-4 sentences) unless the user asks for
detail or the question genuinely requires a longer answer.
3. When the user asks you to remember, save, or note something, you must call
save_note before replying, then confirm briefly. Never tell the user you
saved it unless you actually called save_note in this turn.
4. When the user asks "what do I have saved about X?", search both notes
(find_notes) and Retrieval (search_knowledge).
5. For web searches, summarize the findings clearly. Do not dump raw results.
6. When storing knowledge, pick a descriptive entry_id so it can be updated later.
7. Never include JSON, chat_id, or any technical wrapper in your replies.
8. Match the user's language. If they write in German, reply in German. If
English, reply in English.
## Telegram Formatting (HTML only)
- <b>bold</b> for emphasis
- <i>italic</i> for light emphasis
- <code>inline code</code> for technical terms
- <pre>code blocks</pre> for multi-line code
Do not use markdown formatting (asterisks, underscores). Only use the HTML
tags listed above.
temperature: 0.2
max_iterations: 15
timeout: 120
session:
key: context.telegram_chat_id
# Chats run for months; compact old session history instead of hitting context limits.
context_compression:
enabled: true
keep_recent_messages: 10
session_history:
interval: 8
keep_recent_runs: 2
tools:
- web_search
- web_read_page
- assistant_tools.save_note
- assistant_tools.find_notes
- assistant_tools.delete_note
- assistant_tools.search_knowledge
- assistant_tools.remember_knowledge
- assistant_tools.schedule_followupPython-Funktionen, die die Agenten als Tools aufrufen.
"""Personal assistant tools - notes via database, knowledge via RAG."""
from connic.tools import db_insert, db_find, db_delete, retrieval_query, retrieval_store, trigger_agent_at
NOTES_COLLECTION = "notes"
KNOWLEDGE_NAMESPACE = "personal"
async def save_note(title: str, content: str) -> dict:
"""Save a personal note. Use for quick facts, reminders, and things the user wants to remember.
Args:
title: Short label for the note (e.g. "dentist appointment", "wifi password").
content: The note body. Include all relevant details.
Returns:
The saved note document.
"""
result = await db_insert(NOTES_COLLECTION, {
"title": title,
"content": content,
})
return result["inserted"][0]
async def find_notes(query: str = "") -> list[dict]:
"""Search saved notes. Returns up to 20 matching notes ordered by most recent.
Args:
query: Search term to filter by title. Leave empty to list all recent notes.
Returns:
List of matching note documents.
"""
filter_dict = {}
if query.strip():
filter_dict = {"title": {"$regex": query}}
result = await db_find(
NOTES_COLLECTION,
filter=filter_dict,
sort={"_created_at": -1},
limit=20,
)
return result.get("documents", [])
async def delete_note(note_id: str) -> dict:
"""Delete a note by its ID.
Args:
note_id: The _id of the note to delete (from find_notes results).
Returns:
Deletion result.
"""
return await db_delete(NOTES_COLLECTION, filter={"_id": note_id})
async def search_knowledge(query: str) -> list[dict]:
"""Search personal Retrieval for longer-form stored information.
Use this for articles, meeting summaries, reference material, or anything
the user stored with remember_knowledge.
Args:
query: Describe what you're looking for (e.g. "meeting notes from last week").
Returns:
List of matching knowledge entries with content and relevance score.
"""
result = await retrieval_query(query, namespace=KNOWLEDGE_NAMESPACE, max_results=5)
return result.get("results", [])
async def remember_knowledge(content: str, entry_id: str | None = None) -> dict:
"""Store information in personal Retrieval for later retrieval.
Best for longer content like summaries, articles, how-tos, or reference
material. For short facts and reminders, use save_note instead.
Args:
content: The information to store. Be descriptive so it can be found later.
entry_id: Optional stable ID for updates (e.g. "project-roadmap"). If an
entry with this ID exists, it will be replaced.
Returns:
Store result with entry_id.
"""
return await retrieval_store(
content, namespace=KNOWLEDGE_NAMESPACE, entry_id=entry_id
)
AGENT_NAME = "telegram-assistant"
async def schedule_followup(task: str, delay: dict, context: dict) -> dict:
"""Schedule the assistant to follow up later with a reminder or task.
Use when the user asks to be reminded about something, or wants you to
check/do something at a later time (e.g. "remind me in 2 hours",
"check the weather tomorrow morning").
Args:
task: What you should do when the scheduled time arrives. Be specific
so your future self knows exactly what to tell the user.
delay: When to follow up, as a relative offset from now. Dict with keys
d (days), h (hours), m (minutes), s (seconds). At least one required.
Calculate from the current time provided in your input.
Returns:
Confirmation with the scheduled time.
"""
chat_id = context["telegram_chat_id"]
result = await trigger_agent_at(
agent_name=AGENT_NAME,
payload={"chat_id": chat_id, "message": task},
delay=delay,
)
return {
"scheduled": True,
"scheduled_at": result.get("scheduled_at"),
"task": task,
}Läuft vor und nach dem gleichnamigen Agenten.
"""Middleware for telegram-assistant.
Before:
Puts the chat_id from the connector payload into context so the session
key (context.telegram_chat_id) resolves correctly.
Injects the current UTC time so the agent can calculate relative delays.
After:
Wraps the agent reply in {"chat_id": ..., "text": "..."} for the outbound
Telegram connector.
"""
import json
from datetime import datetime, timezone
from typing import Any
async def before(content: dict[str, Any], context: dict[str, Any]) -> dict[str, Any]:
payload = context.get("payload") or {}
chat_id = payload.get("chat_id") if isinstance(payload, dict) else None
context["telegram_chat_id"] = chat_id
now = datetime.now(timezone.utc)
time_part = {"text": f"[Current time: {now.strftime('%Y-%m-%d %H:%M UTC (%A)')}]"}
content["parts"].insert(0, time_part)
return content
async def after(response: str, context: dict[str, Any]) -> str:
chat_id = context.get("telegram_chat_id")
return json.dumps({"chat_id": chat_id, "text": response.strip()})5 Testfälle für connic test.
version: "1.0"
# The six assistant_tools are mocked so no database, Retrieval data, or
# scheduled trigger is touched. web_search and web_read_page are predefined and
# run for real, so strict_mocks is omitted. Each payload carries the top-level
# chat_id the before() middleware extracts into the session key; the after()
# middleware wraps the reply as {"chat_id": ..., "text": ...}, so cases assert on
# the wrapped output structure only.
defaults:
runs: 1
timeout_s: 120
mocks: assistant_mocks
tests:
- name: saves_a_note
payload: '{"chat_id": 12345, "text": "Remember that my wifi password is hunter2"}'
expected_result: output.chat_id == 12345 and output.text != ""
expected_tool_calls:
- assistant_tools.save_note
- name: lists_notes
payload: '{"chat_id": 12345, "text": "What notes do I have?"}'
expected_result: output.text != ""
expected_tool_calls:
- assistant_tools.find_notes
- name: deletes_a_note
payload: '{"chat_id": 12345, "text": "Delete my groceries note"}'
expected_result: output.text != ""
expected_tool_calls:
- assistant_tools.delete_note
- name: remembers_then_recalls
payload: '{"chat_id": 12345, "text": "Save this to Retrieval: our Q3 launch retro concluded the onboarding flow needs a guided tour and clearer empty states. Then tell me what I have stored about the launch retro."}'
expected_result: output.text != ""
expected_tool_calls:
- assistant_tools.remember_knowledge
- assistant_tools.search_knowledge
- name: schedules_a_followup
payload: '{"chat_id": 12345, "text": "Remind me in 2 hours to call mom"}'
expected_result: output.text != ""
expected_tool_calls:
- assistant_tools.schedule_followupInstallieren und bereitstellen
Installiere das Template, erstelle ein connic-Projekt und starte das Deployment über ein verbundenes Git-Repository oder die CLI.
- Voraussetzungen
- Python 3.10+
- Ein connic-Konto mit einem angelegten Projekt
- Projektguthaben für ein connic/* KI-Modell oder Zugangsdaten für einen BYOK Provider
- Deployment mit Git
- Verbinde das Repository unter Projekt Settings → Git & Environments, ordne einen Branch einem Environment zu und pushe.
- Deployment mit der CLI
- Erstelle unter Projekt Settings → API Keys & MCP Auth einen API Key, führe im Projektordner connic login aus und danach connic deploy. Änderungen probierst du vorher mit connic dev und connic test aus.
- Verbinden und konfigurieren
- Erstelle über @BotFather einen Telegram Bot und füge anschließend mit dem Bot Token je eine eingehende und ausgehende Telegram-Verbindung hinzu. Der Webhook wird automatisch registriert. Ein connic/* KI-Modell nutzen oder BYOK-Zugangsdaten unter Projekt Settings → LLM Provider hinterlegen.
Weitere Agent Templates
E-Mail-Helpdesk
Von connicDer E-Mail-Helpdesk fragt Postfächer per IMAP ab, filtert automatische Antworten und klassifiziert Nachrichten nach Anliegen. Kontextbezogene Antwortentwürfe stammen aus dem konfigurierten Retrieval.
KommunikationFortgeschrittenKafka-Betrugserkennung
Von connicTransaktionen in Kafka Streams werden in Echtzeit auf Betrugsrisiken bewertet. Die Bewertung berücksichtigt die Häufigkeit von Transaktionen, geografische Anomalien und kundenspezifische Muster.
SicherheitExperteKundensupport
Von connicKI-gestützte Ticket-Triage mit Sentimentanalyse und RAG-gestützten Antwortentwürfen. Der Agent ordnet Tickets nach Priorität ein, blockiert Spam und speichert neue Lösungen.
KundensupportEinsteigerPostgreSQL-Änderungsbenachrichtigung
Von connicLISTEN/NOTIFY überwacht PostgreSQL-Änderungen, klassifiziert Ereignisse nach Auswirkung und leitet Benachrichtigungen an das richtige Team weiter. Änderungen mit hoher Auswirkung werden für Audits gespeichert.
DevOpsFortgeschrittenRecherche-Assistent
Von connicDer Assistent zerlegt komplexe Recherchefragen in Teilaufgaben und startet spezialisierte Agenten parallel. Er führt Informationen aus dem Web und internen Quellen zu strukturierten Berichten zusammen und bewertet die Verlässlichkeit der Ergebnisse.
RechercheExperteVoice-Kundensupport
Von connicEntwickle einen Voice-Agenten, der dein Kundenwissen in connic retrieval durchsucht und mit einem Mock-Tool die Ticketerstellung demonstriert.
KundensupportEinsteiger