Metadata-Version: 2.4
Name: llmopenfinance
Version: 0.1.1
Summary: Console chat with an LLM financial assistant over your Open Finance (Pluggy) data
Author: Jorge Albuquerque
License: MIT
Keywords: open finance,pluggy,llm,pyllmrouter,ollama,claude,duckdb,personal finance
Classifier: Development Status :: 3 - Alpha
Classifier: Environment :: Console
Classifier: Intended Audience :: End Users/Desktop
Classifier: Programming Language :: Python :: 3.12
Requires-Python: >=3.12
Description-Content-Type: text/markdown
License-File: LICENSE
Requires-Dist: duckdb>=2.0.1
Requires-Dist: httpx>=0.28.1
Requires-Dist: pyllmrouter[all]>=0.4.2
Requires-Dist: rich>=15.0.0
Requires-Dist: typer>=0.29.2
Provides-Extra: web
Requires-Dist: flask>=3.1.3; extra == "web"
Requires-Dist: waitress>=3.0.2; extra == "web"
Dynamic: license-file

# llm open finance

Talk to your own bank data from the terminal. `llmopenfinance` is a web chat with an LLM financial assistant
(**Claude**, **Codex**, **Gemini** (no paid API, using only regular OAUTH sign-in) or a local **Ollama** / **llama.cpp**
model (recommended for privacy), all through [pyllmrouter](https://github.com/fortalbrz/pyllmrouter)). It answers questions about your accounts, credit cards, investments and
loans, using data pulled through:

 - **Open Finance US** via [Teller](https://teller.io/).
 - **Open Finance Brasil** via [Pluggy](https://pluggy.ai).
 
The responses are consistent (and free of hallucinations), generated by a local, deterministic SQL process.


- [[Documentação em Português (pt-BR)](README.pt-BR.md)]

![web client](docs/img/img001.png)

 

```text
$ llmopenfinance
Financial assistant ready. Commands: /help  /summary (data sent to the model)  /sync  /reset  /history  exit
======================================================================

You: Which subscriptions do I have?

Assistant:
 ↳ consultando detect_subscriptions(months=12)
  | Service | Value   | Last charge     | Annual cost |
  |---------|---------|-----------------|-------------|
  | Netflix | $  8.99 | 2026-11-08      | $  107.88   |
  | Spotify | $  6.99 | 2026-11-12      | $   83.88   |
...
```

Example questions (answers are in Brazilian Portuguese by default; set `LLMOPENFINANCE_LANG=en` for English,
see [Language](#language)):

- *what services do I subscribe to?*
- *how much do I spend on online shopping each month?*
- *how can I improve my finances?*
- *what were my 3 largest expenses in November?*
- *how much is left on my loan, and what is its total effective cost?*


## Open Finance US

  - TODO

## Open Finance Brasil

### Connecting Banks in "My Pluggy" and Generating Tokens (Brazilian Open Finance)

Before you begin:
1. Connect your bank accounts via Open Finance in **Meu Pluggy** ( [meu.pluggy.ai](https://meu.pluggy.ai) ) - Brazilian Open Finance.
2. Obtain your credentials (`Client ID` and `Client Secret`) from the **Pluggy Dashboard** ( [dashboard.pluggy.ai](https://dashboard.pluggy.ai) ).

---

### Part 1: How to connect your banks via Open Finance (`meu.pluggy.ai`)

**Meu Pluggy** ( [meu.pluggy.ai](https://meu.pluggy.ai) ) is Pluggy’s free portal designed for **personal use** (tracking expenses, populating spreadsheets, feeding your own systems, or providing data to AI agents using information from your own accounts).

> **Important:** Pluggy is an institution regulated by the Central Bank of Brazil. Data sharing is handled directly through your bank’s official Open Finance flow.

#### Step 1: Create your "Meu Pluggy" account
1. Go to [https://meu.pluggy.ai](https://meu.pluggy.ai).
2. Create a new account using your **email** and a **password**.
3. Registration is immediate (self-service); no invitation or manual approval is required.

#### Step 2: Initiate the connection with your bank
1. Once logged into the "Meu Pluggy" dashboard, click the **"Connect My Account"** button.
2. In the list of financial institutions, search for and select the bank you wish to connect (e.g., Nubank, Itaú, Inter, Banco do Brasil, Bradesco, Santander, etc.).

#### Step 3: Authorize data sharing via Open Finance
1. You will be automatically redirected to your bank’s **official app or website**.
2. Log in to your bank as you normally would and review the data-sharing permissions (balances, statements, cards, investments).
3. Confirm the authorization within your bank’s interface.

> ⚠️ **Important (Common cause of errors):** Stay on the final confirmation screen provided by your bank and **wait for the automatic redirect back to Meu Pluggy**. Closing the app or navigating back manually before the process is complete will cancel the connection.

#### Step 4: Verify that the connection is complete
1. Once back on the Meu Pluggy dashboard, check that the account appears in your list, showing both your **balance** and **transaction history (statement)**.
2. If the account does not appear, please repeat the authorization process.
3. Do you have accounts at other banks? Simply click **"Connect My Account"** again and repeat the process for each institution.

---

### Part 2: How to create credentials and generate tokens (`dashboard.pluggy.ai`)

To consume data via the API (or integrate it into external tools), you will need to create an application in the **Pluggy Dashboard**, obtain your credentials, and generate an authentication token.

#### Step 1: Create your Dashboard account
1. Go to [https://dashboard.pluggy.ai](https://dashboard.pluggy.ai).
2. Register your account — **it is recommended to use the same email address** you registered with on `meu.pluggy.ai`.
3. *Note:* If a notice regarding a trial period (e.g., 15 days) appears, you can disregard it for the personal use flow integrated with "Meu Pluggy."

#### Step 2: Create an Application
1. In the Dashboard menu, go to the **Applications** section and click to create a new application.
2. Give it an identifying name (e.g., `My Personal Finances`).
3. A single application is sufficient to access all the bank accounts you connected in Part 1.

#### Step 3: Copy the `Client ID` and `Client Secret`
1. Open the newly created application and go to the **"Application"** tab (or the credentials settings section).
2. Locate and copy the following two values:
   - **`Client ID`**: The unique identifier for the application (in UUID format).
   - **`Client Secret`**: The application's secret key (new keys typically begin with `pluggy_sk_`).

> 🔒 **Security best practices:**
> - The `Client Secret` may only be displayed **once**—at the moment of creation. Store it in a secure location (such as a password manager or an `.env` file). If you lose it, you will need to rotate it or generate a new one via the Dashboard. > - **Never** expose the `Client Secret` in front-end code, mobile applications, or public repositories (GitHub).



## Quick start

```powershell
# 1. Install (uv only)
uv sync

# 2. Credentials (Pluggy application clientId/clientSecret from dashboard.pluggy.ai)
$env:PLUGGY_USERNAME = "<clientId>"
$env:PLUGGY_PASSWORD = "<clientSecret>"

# 3. One LLM provider (see "LLM providers" below): an API key, a sign-in or a local server
$env:ANTHROPIC_API_KEY = "<key>"                # e.g. Claude through the Anthropic API

# 4. Connect your banks (MeuPluggy, free for personal use) — see docs/pluggy-setup.md
uv run llmopenfinance items add <item-id>       # item ids copied from the Pluggy dashboard
#   or: uv run llmopenfinance connect           # opens the Pluggy Connect widget in your browser

# 5. Chat (syncs first)
uv run llmopenfinance                           # auto-detects the first usable provider
uv run llmopenfinance --provider anthropic      # a specific provider
uv run llmopenfinance --provider ollama --model qwen3.5:9b   # 100% local
```

## LLM providers

The LLM layer is [pyllmrouter](https://github.com/fortalbrz/pyllmrouter), which is the only LLM service this project uses
(it is installed from GitHub with the project: `uv sync`). Pick the provider with `--provider <name>`, the
`LLMOPENFINANCE_PROVIDER` variable, or leave it out to let pyllmrouter auto-detect.

| `--provider` | Backend | Needs |
|---|---|---|
| `claude-agent-token` | Claude Agent SDK, long-lived token | `CLAUDE_CODE_OAUTH_TOKEN` |
| `claude-agent-login` | Claude Agent SDK, Claude CLI login | `claude auth login` |
| `anthropic` (alias `claude`) | Anthropic Messages API | `ANTHROPIC_API_KEY` |
| `gemini` | Gemini API | `GEMINI_API_KEY` |
| `antigravity` | Gemini through the Antigravity CLI (`agy`) | `agy` signed in |
| `codex` | OpenAI Codex (ChatGPT plan or API key) | `codex login` |
| `ollama` | Local Ollama server | a running server (`OLLAMA_SERVER`) |
| `llamacpp` | Local llama.cpp `llama-server` | a running server (`LLAMACPP_SERVER`) |

- **Chosen explicitly** (`--provider`, or `LLMOPENFINANCE_PROVIDER`): that provider is used, never replaced. An unknown
  name stops the program with exit status 2 and the list of valid names; an unusable one (missing key, SDK or server)
  is reported before the chat starts.
- **Not chosen** (or `auto`): pyllmrouter reads its own `LLMROUTER_PROVIDER` variable and otherwise probes the providers
  in the order of the table and uses the first one that works. A machine with `ANTHROPIC_API_KEY` set therefore picks
  Claude; use `--provider ollama` to stay local.
- `--model` (or the provider's own variable, e.g. `OLLAMA_MODEL`) picks the model; empty means the provider's default.
- `uv run pyllmrouter providers` shows why each provider is or is not available. pyllmrouter accepts more aliases
  (`llama.cpp`, `google`, ...): `uv run pyllmrouter describe` lists them all.
- pyllmrouter is a plain chat API, so the tools are called through a small text protocol that works the same on every
  provider (see [docs/architecture.md](docs/architecture.md#how-tools-are-called)). Small local models follow it less
  reliably than the large hosted ones.

## Commands

| Command | What it does |
|---|---|
| `llmopenfinance` / `llmopenfinance chat` | Interactive chat. Syncs first; skip with `--no-sync` |
| `llmopenfinance server [--host H] [--port N]` | Serves the same chat as a local web page (needs `uv sync --extra web`) |
| `llmopenfinance ask "pergunta"` | Asks one question and exits |
| `llmopenfinance sync [--force]` | Downloads accounts, transactions, card bills, investments and loans |
| `llmopenfinance status` | Shows connections, consent expiry dates and local row counts |
| `llmopenfinance connect [--sandbox]` | Connects accounts through the Pluggy Connect widget on a local page |
| `llmopenfinance items add/list/remove` | Manages the registered Pluggy item ids |

Global options: `--provider <pyllmrouter provider>|auto`, `--model <id>`, `--db <file>`, `-v`.
See [docs/usage.md](docs/usage.md) for the full reference.

## Language

The application speaks Brazilian Portuguese (`pt-BR`, the default) or English (`en`): the command help, every message,
the assistant's system prompt and its answers. Pick one with the `LLMOPENFINANCE_LANG` environment variable. There is
no command-line option for it.

```powershell
$env:LLMOPENFINANCE_LANG = "en"    # or "pt-BR"
uv run llmopenfinance
```

- English shows money as `R$ 1,234.56` and dates as `YYYY-MM-DD`. Portuguese keeps `R$ 1.234,56` and `DD/MM/AAAA`.
- An unsupported value stops the program with a short message on stderr and exit status 2.
- Stored data such as category labels (`Alimentação`) is never translated, and the chat commands of both languages
  (`/ajuda` and `/help`, `/resumo` and `/summary`, `sair` and `exit`) work in either.

## Web chat

`llmopenfinance server` serves the same assistant as a chat page in your browser, with buttons for `/help`, `/summary`,
`/sync`, `/reset` and `/history` and a language that follows `LLMOPENFINANCE_LANG`. It needs the optional `web` extra
(Flask and Waitress):

```powershell
uv sync --extra web
uv run llmopenfinance server                    # syncs, prints a URL with a token and opens the browser
uv run llmopenfinance server --no-browser --no-sync --port 8123
```

Options: `--host` (default `127.0.0.1`), `--port` (`8000`), `--threads` (`4`, at least 2), `--browser/--no-browser`,
`--sync/--no-sync` and `--sql/--no-sql` (the last two work as in `chat`); the global `--provider` and `--model` choose
the LLM. Without the extra the command prints the install line and exits with status 1.

Security, in short (details in [docs/usage.md](docs/usage.md#server)):

- It listens on the loopback address only, unless you pass another `--host`; the page then travels over **plain HTTP**
  and `server` prints a warning. With a wildcard host (`0.0.0.0`, `::`) the token alone protects access.
- Every launch creates a new secret token. The URL with the token (`http://127.0.0.1:8000/?token=...`) is printed once
  and never logged; the browser keeps it in an `HttpOnly` cookie and the address bar drops it.
- Requests whose `Host` header is not this server are refused (DNS-rebinding defence).
- One server process holds one conversation, shared by every tab. A request that arrives while the assistant is busy is
  refused with "busy"; requests are not queued.

## How it works

```text
Pluggy API ──sync──▶ DuckDB (local) ──read-only──▶ tools ◀──tool calls── LLM (any pyllmrouter provider)
                         │                                                    ▲
                         └──── financial snapshot (aggregates) ───────────────┘ system prompt
```

- **Sync** (`sync.py`) pulls each item's full history. It is incremental per item and skips unchanged items.
  A failing item or product is reported, and the rest of the sync continues.
- **Local enrichment** (`categorize.py`):
  - Every transaction gets a pt-BR category and a *kind*: expense, refund, income, transfer or investment.
  - Card bill payments and transfers between your own accounts are never counted as spending.
  - This works even after Pluggy's paid categorization stops at the end of the trial.
- **Assistant** (`agent.py`, `tools.py`, `analytics.py`):
  - The system prompt carries a compact snapshot of your finances.
  - The model calls deterministic SQL tools to get the details, so the numbers it gives come from your data.
  - For remote providers there is also a guarded `run_sql` escape hatch (off by default for local ones).

Details: [docs/architecture.md](docs/architecture.md).

## Privacy

With a local provider (`ollama` or `llamacpp`) nothing leaves your machine except the Pluggy sync itself. With any
other provider, the snapshot and the rows returned by tools are sent to that provider's service, and the chat prints a
notice saying so. Each tool result is capped at 100 rows, but `run_sql` (on by default for remote providers) can select
any column, including the full raw Pluggy record of a transaction. Use `--no-sql` to limit the model to the curated
tools. The local database
lives at `~/.llmopenfinance/finance.duckdb` (change it with `--db` or `LLMOPENFINANCE_DB`).

## Development

```powershell
uv run ruff format . ; uv run ruff check . ; uv run pyrefly check ; uv run pytest
```

The tests use synthetic Pluggy payloads, `httpx.MockTransport` and a pyllmrouter chat with a scripted backend, so they never touch the network.
The coverage gate is 90%. See [AGENTS.md](AGENTS.md).

## Author

- **[Jorge Albuquerque](mailto:quantamentalguy@gmail.com)**, Ph.D. [[LinkedIn](https://www.linkedin.com/in/jorgealbuquerque)] [[X](https://x.com/quantamentalguy)]
- GitHub: [fortalbrz/llmopenfinance](https://github.com/fortalbrz/llmopenfinance)
- Companion project: [fortalbrz/pyllmrouter](https://github.com/fortalbrz/pyllmrouter) – the LLM layer, reusable in other projects
- Also, check out the [ollama2cpp](https://github.com/fortalbrz/ollama2cpp) project for a simple and optimized migration from the local LLM server [ollama](https://ollama.com/) to [llama-cpp](https://llama-cpp.com/) (increase your local token generation rate by tunning algorithm).

## License

[MIT](LICENSE)

The companion project [pyllmrouter](https://github.com/fortalbrz/pyllmrouter) is MIT-licensed too.
