Skip to main content
Glama
vinimeurer

orcamento

by vinimeurer

对话式预算 — 核心流水线

通过 Telegram 使用自然语言记录开支的系统,使用 Google Gemini(官方 API,模型可通过 .env 配置,默认为 gemini-3.6-flash)作为语言模型,由 Nanobot 编排,数据保存在 Postgres 中。

本文档假设您从未运行过 Docker,并解释每一步、每个命令以及每个命令的预期结果。


目录

  1. 您需要安装的内容

  2. 获取 Telegram 机器人令牌

  3. 获取 Gemini API 密钥

  4. 配置 .env 文件

  5. 使用 Docker 启动所有服务

  6. 在 Telegram 中测试

  7. 日常命令

  8. 常见问题及解决方法

  9. 项目中每个文件的作用

  10. 备选方案:本地安装(不使用 Docker)

  11. 项目后续步骤


Related MCP server: Expense Tracker MCP Server

1. 您需要安装的内容

您的机器上只需要安装一样东西。您不需要单独安装 Python、Postgres 或 Nanobot——所有这些都在容器内运行。

Docker Desktop(Windows/Mac)或 Docker Engine(Linux)

检查一切是否正常

打开终端(Windows 上的 PowerShell,Mac/Linux 上的 Terminal)并运行:

docker --version
docker compose version

您应该看到两行版本信息,没有错误。


2. 获取 Telegram 机器人令牌

  1. 打开 Telegram(手机或桌面),在搜索中查找 @BotFather。这是 Telegram 官方用于创建其他机器人的机器人——请确认它带有已验证徽章。

  2. 向它发送:/newbot

  3. 它会询问您机器人的名称。可以是任何内容,例如:Orçamento Conversacional

  4. 然后它会询问用户名。该用户名必须在整个 Telegram 中唯一,并且必须以“bot”结尾,例如:orcamento_seunome_bot

  5. 如果成功,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...
  6. 复制完整的令牌行(格式为 数字:字母和数字)。您将在下一步将其粘贴到 .env 文件中。

请妥善保管此令牌。


3. 获取 Gemini API 密钥

Nanobot 使用 Google Gemini 官方 API 作为语言模型。

  1. 访问 https://aistudio.google.com/api-keys 并使用您的 Google 帐户登录。

  2. 点击 Create API key(Google 会自动创建一个项目)。

  3. 复制密钥并粘贴到下一步的 .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_PASSWORDDATABASE_URL)已带有可用的值——在 Docker 中运行时无需修改它们。

保存文件。


5. 使用 Docker 启动所有服务

**orcamento-conversacional 文件夹内**(包含 docker-compose.yml 文件的文件夹)打开终端,然后运行:

docker compose up -d --build

该命令按顺序执行的操作:

步骤

发生什么

大约时间

1

从互联网下载基础镜像(Postgres)

1–3 分钟(首次)

2

构建(--build)Nanobot 镜像(包括内置的 MCP 服务器)

2–4 分钟(首次)

3

启动 Postgres 并自动应用 schema.sql

几秒钟

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 中测试

  1. 在 Telegram 中,搜索您在 BotFather 创建的机器人的用户名(例如:@orcamento_seunome_bot)并打开与它的对话。

  2. 发送 /start。在第一次对话中,Nanobot 可能会要求配对代码——它出现在日志中(docker compose logs -f nanobot,行“Generated pairing code ...”)。将该代码发送给机器人。

  3. 发送类似这样的内容:

    Gastei 35 no almoço hoje
  4. 几秒钟后,机器人应回复确认记录,类似:

    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.mdconfig.docker.json.env 之后(无需重建镜像;配置和提示直接挂载到容器中):

docker compose up -d nanobot    # recria o container aplicando o novo .env

编辑 mcp_server/expense_tools.pydb/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 upmake downmake logsmake restartmake 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 日志中出现 401unauthorizedinvalid 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 SDK mcp 2.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. 项目后续步骤

  1. 使用真实消息测试端到端流程,并根据观察到的提取错误(非正式语言、缩写、模糊值)调整 SOUL.md

  2. 添加完整报告工具(期间比较、支出演变)。

  3. 实现推荐层:整合 resumo_por_categoria 的数据,并通过 API 发送给高级 LLM。

  4. 自动将支出与已认证的 Telegram 用户关联(目前 telegram_id 由模型在调用工具时传递)。


关于验证的警告

该流水线已在 Docker 实际运行中验证:容器启动,MCP 通过 stdio 连接并注册了 3 个工具,Postgres 插入已通过 psql 确认。每次启动前都会检查 docker-compose.yml 和配置 JSON 的语法。

如果卡在 docker compose up 上,请从8. 常见问题部分开始。

A
license - permissive license
Not graded
quality - not tested
C
maintenance

Resources

Unclaimed servers have limited discoverability.

Looking for Admin?

If you are the server author, to access and configure the admin panel.

Related MCP Servers

  • F
    license
    Not graded
    quality
    D
    maintenance
    Enables AI assistants to manage personal expenses through natural conversation, supporting expense tracking, categorization, filtering, and financial summaries. Uses SQLite database to store expense records with full CRUD operations for comprehensive personal finance management.
    1
  • F
    license
    C
    quality
    D
    maintenance
    Enables 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
  • F
    license
    Not graded
    quality
    D
    maintenance
    Enables natural language management of personal expenses, including adding, listing, and summarizing expenses with local SQLite storage.

View all related MCP servers

Related MCP Connectors

  • Personal finance by conversation: expenses, receipts, statement import, budgets, net worth.

  • Multi-tenant Telegram gateway for AI agents — HTTP+stdio, 8 tools, MTProto User API

  • Log, query, and edit expenses, budgets, and accounts in Ledgy from any MCP-compatible AI assistant.

View all MCP Connectors

Latest Blog Posts

MCP directory API

We provide all the information about MCP servers via our MCP API.

curl -X GET 'https://glama.ai/api/mcp/v1/servers/vinimeurer/orcamento-conversasional'

If you have feedback or need assistance with the MCP directory API, please join our Discord server