orcamento
对话式预算 — 核心流水线
通过 Telegram 使用自然语言记录开支的系统,使用 Google Gemini(官方 API,模型可通过 .env 配置,默认为 gemini-3.6-flash)作为语言模型,由 Nanobot 编排,数据保存在 Postgres 中。
本文档假设您从未运行过 Docker,并解释每一步、每个命令以及每个命令的预期结果。
目录
Related MCP server: expense-tracker-postgres-mcp
1. 您需要安装的内容
您的机器上只需要安装一样东西。您不需要单独安装 Python、Postgres 或 Nanobot——所有这些都在容器内运行。
Docker Desktop(Windows/Mac)或 Docker Engine(Linux)
Windows 或 Mac:从 https://www.docker.com/products/docker-desktop/ 下载并安装 Docker Desktop——安装后,打开 Docker Desktop 应用程序,等待它显示“Docker is running”(图标在系统托盘中变为绿色/稳定)。
Linux:按照 https://docs.docker.com/engine/install/ 为您的发行版安装,然后按照 https://docs.docker.com/engine/install/linux-postinstall/ 配置,以便无需
sudo即可运行docker。
检查一切是否正常
打开终端(Windows 上的 PowerShell,Mac/Linux 上的 Terminal)并运行:
docker --version
docker compose version您应该看到两行版本信息,没有错误。
2. 获取 Telegram 机器人令牌
打开 Telegram(手机或桌面),在搜索中查找 @BotFather。这是 Telegram 官方用于创建其他机器人的机器人——请确认它带有已验证徽章。
向它发送:
/newbot它会询问您机器人的名称。可以是任何内容,例如:
Orçamento Conversacional。然后它会询问用户名。该用户名必须在整个 Telegram 中唯一,并且必须以“bot”结尾,例如:
orcamento_seunome_bot。如果成功,BotFather 会回复一条类似这样的消息:
Done! Congratulations on your new bot. You will find it at t.me/orcamento_seunome_bot. You can now add a description... Use this token to access the HTTP API: 7123456789:AAHxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx Keep your token secure and store it safely...复制完整的令牌行(格式为
数字:字母和数字)。您将在下一步将其粘贴到.env文件中。
请妥善保管此令牌。
3. 获取 Gemini API 密钥
Nanobot 使用 Google Gemini 官方 API 作为语言模型。
访问 https://aistudio.google.com/api-keys 并使用您的 Google 帐户登录。
点击 Create API key(Google 会自动创建一个项目)。
复制密钥并粘贴到下一步的
.env中。
关于费用:不需要信用卡。免费层涵盖 Flash/Flash-Lite 模型,每分钟/每天有请求限制(约 10 次/分钟,每天约 250–1,500 次,具体取决于模型)——对于此项目来说绰绰有余。Pro 模型是付费的。官方价格表:https://ai.google.dev/gemini-api/docs/pricing
4. 配置 .env 文件
项目自带一个名为 .env 的文件,位于文件夹根目录(orcamento-conversacional/.env)。Docker Compose 会自动读取它——您无需重命名任何内容。
注意:以点开头的文件(.env)在 Windows 资源管理器、Mac 的 Finder 以及 Linux/Mac 的 ls(不带标志)中默认是“隐藏”的。使用 ls -la 在终端中查看,或通过文本编辑器打开文件夹。
在 .env 中,将以下两行替换为实际值:
TELEGRAM_TOKEN=coloque_seu_token_aqui ← token do BotFather (seção 2)
GEMINI_API_KEY=coloque_sua_chave_aqui ← chave do AI Studio (seção 3)变量 GEMINI_MODEL 定义使用哪个模型(默认:gemini-3.6-flash)。仅当您想更换为官方列表中的其他有效 ID 时才修改:https://ai.google.dev/gemini-api/docs/models
其他变量(POSTGRES_PASSWORD、DATABASE_URL)已带有可用的值——在 Docker 中运行时无需修改它们。
保存文件。
5. 使用 Docker 启动所有服务
在**orcamento-conversacional 文件夹内**(包含 docker-compose.yml 文件的文件夹)打开终端,然后运行:
docker compose up -d --build该命令按顺序执行的操作:
步骤 | 发生什么 | 大约时间 |
1 | 从互联网下载基础镜像(Postgres) | 1–3 分钟(首次) |
2 | 构建( | 2–4 分钟(首次) |
3 | 启动 Postgres 并自动应用 | 几秒钟 |
4 | 启动 Nanobot,等待 Postgres 就绪 | 几秒钟 |
您的机器上不会下载或运行模型:Gemini 在 Google 云端运行。
-d 标志(“detached”)使所有内容在后台运行。下次运行 docker compose up -d(不带 --build)时,几秒钟即可启动。
如何知道一切是否正常
运行:
docker compose ps您应该看到 2 个服务:
NAME IMAGE STATUS
orcamento_postgres postgres:16-alpine Up (healthy)
orcamento_nanobot ...nanobot Up同时检查 Nanobot 的日志——应该显示 MCP 已连接:
docker compose logs nanobot查找类似这样的行:
MCP: registered tool 'mcp_orcamento_registrar_despesa' from server 'orcamento'
MCP server 'orcamento': connected, 3 capabilities registered
✓ Health endpoint: http://127.0.0.1:18790/health
bot @seubot connected如果 orcamento_nanobot 显示为“Restarting”或从列表中消失,请参阅常见问题部分。
6. 在 Telegram 中测试
在 Telegram 中,搜索您在 BotFather 创建的机器人的用户名(例如:
@orcamento_seunome_bot)并打开与它的对话。发送
/start。在第一次对话中,Nanobot 可能会要求配对代码——它出现在日志中(docker compose logs -f nanobot,行“Generated pairing code ...”)。将该代码发送给机器人。发送类似这样的内容:
Gastei 35 no almoço hoje几秒钟后,机器人应回复确认记录,类似:
Registrado: R$ 35,00 em alimentação (almoço).
如果机器人没有回复任何内容,请参阅下面的常见问题部分。
7. 日常命令
所有命令都在 orcamento-conversacional 文件夹内运行。
实时查看所有日志:
docker compose logs -f(按 Ctrl+C 退出——这只是停止显示日志,容器仍在运行。)
仅查看 Nanobot 的日志(调试对话最有用):
docker compose logs -f nanobot停止所有服务(保留已保存的数据):
docker compose down停止后再次启动:
docker compose up -d编辑 SOUL.md、config.docker.json 或 .env 之后(无需重建镜像;配置和提示直接挂载到容器中):
docker compose up -d nanobot # recria o container aplicando o novo .env编辑 mcp_server/expense_tools.py 或 db/connection.py 之后(需要重建,因为 MCP 的 venv 是在镜像中创建的):
docker compose up -d --build nanobot彻底删除所有内容,包括数据库数据(如果某些内容损坏且您想从头开始,这很有用):
docker compose down -v进入数据库手动查看已记录的开支:
docker exec -it orcamento_postgres psql -U orcamento -d orcamento在 psql 中,尝试:
SELECT * FROM despesas ORDER BY criado_em DESC LIMIT 10;退出 psql:输入 \q 并按 Enter。
可选快捷方式: 如果您安装了 make(Mac/Linux 上默认),项目包含一个 Makefile,包含最常用的命令:make up、make down、make logs、make restart、make ps。
8. 常见问题及解决方法
Error: Environment variable 'GEMINI_API_KEY' referenced in config is not set
.env 中没有定义 GEMINI_API_KEY 变量。打开 .env,确保该行存在(即使使用临时值),然后重新运行 docker compose up -d nanobot。
Nanobot 日志中出现 401、unauthorized 或 invalid api key
GEMINI_API_KEY 错误、已撤销或包含多余空格。在 https://aistudio.google.com/api-keys 生成新密钥并更新 .env。
429 或速率限制/配额错误
您已达到 Gemini 免费层的限制(每分钟或每天请求数)。选项:等待几分钟,将 .env 中的 GEMINI_MODEL 更改为 Flash-Lite 模型(限制更高,例如:gemini-3.1-flash-lite)并重新启动,或在您的 Google Cloud 帐户中启用计费。
日志中出现 model not found
GEMINI_MODEL 的值不是 Gemini API 的有效 ID。请查看官方列表 https://ai.google.dev/gemini-api/docs/models 并更正 .env。
机器人不调用工具 / 说无法记录
运行 docker compose logs nanobot 并查找:
MCP server 'orcamento': connected— 如果未出现,则内置 MCP 服务器启动失败;请查看该行上方的错误;Max iterations (...) reached— 表示模型进入了工具调用循环;可配置的限制位于 config 的agents.defaults.maxToolIterations中。
机器人在 Telegram 中没有任何响应
发送消息时运行
docker compose logs -f nanobot— 日志中应立即出现一些活动。检查您是否完成了配对(第 6 节,步骤 2)。
docker compose version 显示“unknown flag”或不存在
您拥有旧版 Docker Compose(v1,带连字符:docker-compose)。更新 Docker Desktop,或单独安装 docker-compose-plugin 插件(Linux)。
9. 项目中每个文件的作用
orcamento-conversacional/
├── .env # SUAS credenciais (token do Telegram, chave
│ # do Gemini, senha do banco). Lido
│ # automaticamente pelo docker compose.
├── .env.example # Modelo de referência do .env, sem credenciais reais.
├── docker-compose.yml # Define os containers (postgres, nanobot) e
│ # a ordem de inicialização.
├── Makefile # Atalhos opcionais (make up, make logs, etc).
├── requirements.txt # Dependências Python do servidor MCP (mcp, psycopg2-binary).
│
├── db/
│ ├── schema.sql # Cria as tabelas usuarios, categorias, despesas.
│ │ # Aplicado automaticamente na 1ª subida do Postgres.
│ └── connection.py # Código Python que conecta no Postgres (pool de conexões)
│ # e resolve o usuário do Telegram para um id interno.
│
├── mcp_server/
│ ├── expense_tools.py # As "ferramentas" que o agente de IA usa:
│ │ # registrar_despesa, listar_despesas, resumo_por_categoria.
│ │ # Roda via stdio DENTRO do container do Nanobot.
│ └── Dockerfile # Imagem standalone opcional do MCP server (modo HTTP).
│
└── nanobot_config/
├── config.json # Config do Nanobot para rodar FORA do Docker
│ # (instalação local — ver seção 10). MCP via stdio
│ # relativo à raiz do projeto.
├── config.docker.json # Config do Nanobot para rodar DENTRO do Docker —
│ # é este que está ativo quando você usa `docker compose up`.
│ # MCP via stdio em /opt/mcpvenv (venv isolado).
├── Dockerfile # Como construir a imagem do Nanobot. Instala o
│ # nanobot + um venv isolado (/opt/mcpvenv) com as
│ # dependências do servidor MCP.
├── SOUL.md # As instruções que dizem ao agente COMO se comportar:
│ # como extrair valor/categoria/data de uma mensagem,
│ # quando pedir confirmação, o que ele NÃO deve fazer ainda.
├── AGENTS.md # Regras gerais de comportamento (idioma, uso de tools,
│ # tratamento de erro). Complementa o SOUL.md.
└── USER.md # Perfil do usuário — começa vazio, o Nanobot vai
preenchendo automaticamente com o tempo.当前架构详情
语言模型:Google Gemini 通过官方 API(
providers.gemini)。模型由.env中的GEMINI_MODEL变量选择(默认:gemini-3.6-flash)。本地不运行任何模型。MCP 服务器:作为子进程(stdio)在 Nanobot 容器内运行,使用隔离的 venv
/opt/mcpvenv。为什么隔离?工具使用的 Python SDKmcp2.x 与 nanobot 本身要求的版本(mcp>=1.26,<2)冲突。循环保护:
agents.defaults.maxToolIterations: 6限制代理在同一轮中连续调用工具的次数。
为什么有两个 Nanobot 配置文件?
config.json(用于在 Docker 外部本地运行)通过相对于项目根目录的 stdio 指向 MCP 服务器。config.docker.json(在 Docker 内部使用)使用容器的绝对路径(/opt/mcp_server/...)和 venv /opt/mcpvenv/bin/python3。
10. 备选方案:本地安装(不使用 Docker)
如果您更愿意直接在机器上运行 Postgres/Nanobot 而不是在容器中(配置更麻烦,但更容易逐行调试):
10.1. 仅在 Docker 中启动 Postgres
docker compose up -d postgres(这只会启动 仅 Postgres。schema.sql 会自动应用。)
10.2. 安装 MCP 服务器的 Python 依赖
python3 -m venv .venv
source .venv/bin/activate # Windows: .venv\Scripts\activate
pip install -r requirements.txt在同一终端中导出环境变量:
export DATABASE_URL=postgresql://orcamento:orcamento@localhost:5432/orcamento
export TELEGRAM_TOKEN=seu_token_aqui
export GEMINI_API_KEY=sua_chave_aqui
export GEMINI_MODEL=gemini-3.6-flash(在 Windows PowerShell 中,使用 $env:DATABASE_URL = "..." 等。)
10.3. 安装并运行 Nanobot
pip install -U nanobot-ai将 nanobot_config/config.json 复制到 ~/.nanobot/config.json,将 nanobot_config/SOUL.md 复制到 ~/.nanobot/workspace/SOUL.md(如果 workspace 文件夹不存在,请创建)。
从项目根目录运行(config.json 中的 MCP 服务器路径相对于该目录):
nanobot gateway --config nanobot_config/config.json --verbose无需 Telegram 进行测试(对调试提取很有用)
nanobot agent -c nanobot_config/config.json -m "Paguei 120 no mercado no cartão hoje"11. 项目后续步骤
使用真实消息测试端到端流程,并根据观察到的提取错误(非正式语言、缩写、模糊值)调整
SOUL.md。添加完整报告工具(期间比较、支出演变)。
实现推荐层:整合
resumo_por_categoria的数据,并通过 API 发送给高级 LLM。自动将支出与已认证的 Telegram 用户关联(目前
telegram_id由模型在调用工具时传递)。
关于验证的警告
该流水线已在 Docker 实际运行中验证:容器启动,MCP 通过 stdio 连接并注册了 3 个工具,Postgres 插入已通过 psql 确认。每次启动前都会检查 docker-compose.yml 和配置 JSON 的语法。
如果卡在 docker compose up 上,请从8. 常见问题部分开始。
This server cannot be deployed
Maintenance
Related MCP Connectors
Log expenses, receipts and mileage from chat: auto-categorise, split VAT, summarise, export, rebill.
Log expenses, receipts and mileage from chat: auto-categorise, split VAT, summarise, export, rebill.
Log expenses, receipts and mileage from chat: auto-categorise, split VAT, summarise, export, rebill.
141Track expenses from your AI chat: log, categorize, monthly CSV reports. All data is local.
Related MCP Servers
- FlicenseCqualityDmaintenanceEnables AI assistants to manage personal finances by storing, analyzing, and exporting expense data using a persistent PostgreSQL database. Supports adding/editing expenses, generating spending summaries, detecting top categories, and creating monthly reports.12-
- FlicenseNot gradedqualityDmaintenancePersistent expense tracker backed by Neon Postgres with SQL tools for adding, editing, deleting, and analyzing expenses via natural language.-
- FlicenseNot gradedqualityCmaintenanceAI-powered expense tracking MCP server that connects LLM clients to PostgreSQL for natural language expense management.-
- AlicenseNot gradedqualityBmaintenanceEnables users to record and retrieve expenses through natural language, with support for categories, dates, and descriptions, backed by a Postgres database.MIT