# Runbook: chat with the strategy Chat lets the operator ask the desk about its own record: what it holds, what it did in a window, why a decision was made, what the strategy is allowed to do, and whether a sleeve is halted. **The rule that makes it safe:** every factual claim comes from a read-only tool call into the desk's stores, and every answer carries the ids of the records it used. If the records do not contain the answer, the answer is a refusal — never a reconstruction. See ADR-0029. ## What it can answer | Question | Records read | |---|---| | "What do I hold?" / "How much cash?" | ledger folded to the desk's latest record | | "What did you do last week?" | ledger events, orders, decisions in the anchored window | | "Why did you hold INFY?" | decisions (model, prompt digest, tokens, evidence), spec constraints | | "Why did you sell INFY?" | ledger fills; refuses with the window if no sale is recorded | | "What are you allowed to buy?" | strategy spec: universe, max positions, scope, capabilities | | "Is the sleeve halted? Why?" | halt record | ## What it cannot answer - **Hypotheticals.** "What would you do if the Nifty fell 10%?" has no record, so it is refused. This is the known poor answer: a confident guess would read better and would be a lie. - **Arithmetic the desk did not record.** The model may not compute a return, a percentage or a total. If the figure is not a stored snapshot field, the answer is `NO_RECORD`. - **Anything outside the conversation's scope.** A sleeve conversation never sees another sleeve, even if the question names it. A desk conversation sees every sleeve. - **Actions.** It cannot place, cancel, move, halt or edit. It says what would need approval and stops. There is no confirm path here; use the runner/CLI. ## Budget Each conversation gets its own budget (default 12 calls / 60,000 tokens). Every answer and every refusal ends with a visible line: ``` this conversation has used 2 calls / 1,780 tokens (limits: 12 calls / 60000 tokens) ``` A cache hit is free and does not consume budget: the same question against unchanged records reuses the stored completion. The window is anchored to the newest record, so a new cycle changes the prompt and the answer is recomputed. When the budget is exhausted the answer is a refusal naming the usage; start a new conversation to continue. Nothing is silently trimmed and there is no fallback to the model's own knowledge. ### Chat's budget is not the strategy's The chat has its own knobs, named after chat and read once at construction. They are separate from `AgentBudget` (the per-cycle strategy budget) in both directions: exhausting the chat's allowance does not refuse a strategy cycle, and an exhausted strategy budget does not touch the chat. A test holds both directions. | Variable | Default | Meaning | |---|---|---| | `TAPEBOOK_CHAT_MAX_CALLS_PER_TURN` | `4` | provider calls one answer may make (phase 1 makes one; room for tool loops) | | `TAPEBOOK_CHAT_MAX_CALLS_PER_CONVERSATION` | `12` | the outer cap the visible usage line reports | | `TAPEBOOK_CHAT_MAX_TOKENS_PER_CONVERSATION` | `60000` | input + output tokens across the whole conversation | | `TAPEBOOK_CHAT_MONTHLY_CAP` | unset | desk-level monthly cap **in minor units** (paise for INR); unset means no cap | | `TAPEBOOK_CHAT_EFFORT` | `medium` | `low`, `medium` or `high`, recorded on every turn | | `TAPEBOOK_CHAT_PROVIDER` | derived | label for the record; derived from the model's vendor prefix otherwise | | `TAPEBOOK_CHAT_CURRENCY` | `INR` | the currency chat costs are reported in | A cache hit is checked before the budget and is allowed even when the month's cap is reached: a free answer must not be refused for being unaffordable. An exhausted limit refuses with the number, never a silent truncation. ## What a chat call costs Prices are configuration, never a table in the code, because a hard-coded rate is a wrong number the day a vendor changes one: ```sh TAPEBOOK_LLM_PRICES="deepseek/deepseek-flash=10/30,openai/o3-mini=150/600" ``` Each entry is `model=input_per_million/output_per_million`, comma separated, in `TAPEBOOK_CHAT_CURRENCY`'s major units. A model name may contain `/`; the split is on the first `=`. A malformed entry is refused at startup and the message names the entry and the expected shape — a silently dropped entry would turn a priced model into an unpriced one without anyone asking. The price applies to the **turn** and is stored beside the cost in `chat_spend`, so a later rate change does not rewrite what an old call cost. Three cases, and they are different claims: | Situation | `price_source` | `cost_minor` | What it means | |---|---|---|---| | model priced, cache miss | `configured` | the computed cost | money was spent | | model **unpriced**, cache miss | `unknown` | `NULL` | tokens recorded, **cost not configured** — never zero | | cache hit | `configured` (or `unknown` if unpriced) | `0` | a *known* zero: the hit was free | "Cost not configured" is the honest answer for a model with no entry in `TAPEBOOK_LLM_PRICES`. Reporting zero there would be a claim that the call was free, which nobody measured. Add the model to `TAPEBOOK_LLM_PRICES` to turn its tokens into a figure. ## Effort, and when it is only a label Every turn records the provider, model and effort it was answered with, so a mid-conversation switch is visible on the turn it applied to and earlier turns keep theirs. The model and effort are configuration (`TAPEBOOK_LLM_MODEL`, `TAPEBOOK_CHAT_EFFORT`), never hard-coded in the service. The OpenAI-compatible adapter sends `reasoning_effort` only to families known to accept it (`TAPEBOOK_LLM_EFFORT_MODELS`, default `o1,o3,o4,gpt-5`; matches either the whole model name or the part after the last `/`). For anything else the parameter is **not sent** — an unknown field is a 400 and a wasted call — and the turn records the effort with `effort_applied = false`: the label is advisory. A reader can therefore tell "thought hard" from "was asked to think hard". ## Where operator spend is shown Chat's cost is the operator's, and it is **never** a sleeve's cost. It does not appear in any sleeve's `agent_credits` line or forward record; a sleeve's net-of-costs figure is unchanged by a chat turn (a test asserts the figure is byte-identical before and after one). The desk-level monthly figure is planned for the main page in phase 5. Until then, read it directly: ```sql -- Total since the first of the month, by model. cost_minor is NULL when unpriced. SELECT model, count(*) FILTER (WHERE NOT cached) AS paid_calls, count(*) FILTER (WHERE cached) AS cached_calls, sum(input_tokens + output_tokens) FILTER (WHERE NOT cached) AS tokens, sum(cost_minor) AS cost_minor, count(*) FILTER (WHERE cost_minor IS NULL) AS unpriced_calls FROM chat_spend WHERE created_at >= date_trunc('month', now()) GROUP BY model ORDER BY cost_minor DESC NULLS LAST; ``` `operator_spend(connection, *, since=…)` in `adapters/persistence/chat.py` is the same query as a function; it groups by model and currency and sums to the rows. A total with any `unpriced_calls` is incomplete, and the UI must say so rather than print a flattering number. ## Reading a refusal - `The desk has no record of an INFY sale in this sleeve. I searched … from … to … (7 days).` The ledger and orders were searched; the window is stated so the reader can widen it and ask again ("… in the last 90 days"). - `There is no sleeve named 'x' in this desk. Known sleeves: …` The scope does not exist. Check `tape positions` or the runner config. - `The desk has no recorded cycle or ledger event for sleeve x, so there is no window to search.` The sleeve exists in config but has never run. - `This conversation's model budget is exhausted …` Start a new conversation. - `The model's reply could not be tied to the desk's records, so it has been withheld …` The provider stated a number not in the evidence, cited nothing, or cited an item it was not given. The reply is not shown; ask a narrower question. - `I cannot place an order, move money, halt a sleeve, or change the strategy spec …` The question was an instruction. Approve the action through the runner/CLI. ## Audit a conversation The transcript is append-only. Each exchange shares a `turn_index`; `role` separates the question from the answer, and every tool call keeps its arguments and a digest of its result. ```sql SELECT c.id, c.scope_kind, c.sleeve, c.provider, c.model, c.effort, t.turn_index, t.role, t.provider AS turn_provider, t.model AS turn_model, t.effort AS turn_effort, t.effort_applied, t.cached, t.input_tokens + t.output_tokens AS tokens, t.cost_minor, t.cost_currency, t.price_source, t.content FROM chat_conversations c JOIN chat_turns t ON t.conversation_id = c.id WHERE c.sleeve = 'momentum-in' ORDER BY c.created_at, t.turn_index, CASE t.role WHEN 'user' THEN 0 ELSE 1 END; SELECT name, arguments, result_digest FROM chat_tool_calls WHERE conversation_id = 'chat-…' AND turn_index = 0 ORDER BY call_index; SELECT turn_index, model, effort, cached, input_tokens, output_tokens, cost_minor, cost_currency, price_source FROM chat_spend WHERE conversation_id = 'chat-…' ORDER BY turn_index; ``` `effort_applied = false` means the effort was advisory: the provider cannot take a `reasoning_effort` parameter, so the label never reached the model. `price_source = 'unknown'` with `cost_minor IS NULL` means the model is not in `TAPEBOOK_LLM_PRICES`; it is not a zero. If an answer looks wrong, do not edit it. Read the `Sources:` section and the tool calls, then ask a narrower follow-up. A correction is a later turn. ## Wiring the API The routes are registered on a sub-application mounted at `/api` in `entrypoints/api.py`: | Route | Body | Answer | |---|---|---| | `POST /api/chat` | `{"sleeve": "momentum-in" \| null, "question": "…"}` | creates the conversation and asks the first question | | `POST /api/chat/{conversation_id}` | `{"question": "…"}` | follow-up in the same fixed scope | | `GET /api/chat/{conversation_id}` | — | the append-only turns | `"sleeve": null` (or omitted, or `"desk"`) is a desk conversation. A sleeve name this desk has no records for is a `404`, not an empty conversation. The answer body is the service's own record of what happened: ```json { "conversation_id": "chat-…", "turn_index": 0, "text": "… answer …\n\nSources:\n- E1: …\n\nthis conversation has used 1 calls / 890 tokens (limits: 12 calls / 60000 tokens)", "refusal": false, "cached": false, "budget": {"calls": 1, "cached_calls": 0, "total_tokens": 890, "max_calls": 12, "max_tokens": 60000}, "tool_calls": [{"name": "positions_at", "arguments": {"sleeve": "momentum-in", "at": "…"}, "result_digest": "…"}] } ``` `text` already carries the answer, its `Sources:` and the budget line. `tool_calls` is the same set written to `chat_tool_calls`, so an answer can be audited without trusting its prose. The service is built lazily on the first chat request (`_chat_service` in `api.py`) over the stores already on `app.state.connection`: ```text ledgers PostgresLedgerStore orders PostgresOrderStore decisions PostgresDecisionStore snapshots PostgresSnapshotStore halts PostgresHaltStore transcripts PostgresChatStore model CachedModel(inner=build_model(connection)[0], cache=build_model(...)[1], budget=AgentBudget()) model_name from build_model(connection)[2] ``` `build_model` resolves provider, model and effort through `app.llm_settings` (ADR-0052): the stored row when one exists, otherwise `TAPEBOOK_LLM_PROVIDER` / `TAPEBOOK_LLM_MODEL` / `TAPEBOOK_LLM_EFFORT`. **If the selected provider's key is unset, `POST /api/chat` and the follow-up return `503` naming `TAPEBOOK_LLM_API_KEY_` (or the shorthand `TAPEBOOK_LLM_API_KEY` for the provider `TAPEBOOK_LLM_PROVIDER` names); there is no fallback to another provider and none to the model's own knowledge.** `GET /api/chat/{id}` reads the transcript directly from `PostgresChatStore` and still works without a key. `StrategyChat` reads the chat settings (`TAPEBOOK_CHAT_*`, `TAPEBOOK_LLM_PRICES`) once when it is constructed and applies the configured effort to the provider when the adapter can take one. The model and effort it records are configuration; there is no model name in the service's code. Two limits of this wiring, stated because they are visible in a `strategy_spec` tool call: - **`specs` is empty.** The API process does not load the runner's strategy YAML, and there is no spec registry in the database. A conversation still answers from the ledger, orders, decisions, snapshots and halts; `strategy_spec` says "not recorded" rather than inventing a universe. - **Chat is not behind `TAPEBOOK_API_TOKEN`.** It reads the desk and appends only to the chat transcript; the token-gated mutating route is the stock-plan import. If an operator wants chat behind the same token, apply `_authorise` in both chat POST handlers — nothing else changes. Do not add a tool, a route or a prompt branch that can place an order, move money, halt a sleeve or edit a spec. The safety property is that there is no such code path, not that the model declines. ## Operate it cheaply - Ask the narrowest question you need; a named instrument and a window produce less evidence. - A repeated question on unchanged records is a cache hit and costs nothing. - A conversation's budget is per conversation on purpose: a long-running interrogation does not inherit yesterday's spend, and a restarted API re-derives the same usage from the transcript. - No provider key is ever printed by this path. The provider adapter owns the key; the chat service sees only `LLMPort`.