Zero Labs
Industry News / AI

Spec-Driven AI Wealth Manager

Source · Towards AI By Saurabh Kohli

From the publisher’s feed, collected in the ZeroLabs newsroom.

GraphQL, a PyAgent blueprint, and deterministic tax math using OracleOne laptop, one portfolio, and a notebook full of notes: the full setup for the weekend experiment described below.Disclaimer: I am not a financial advisor. This was a weekend experiment fueled by cold brew and out of curiosity. Do not trust this with real money.I tried the following combination of technologies:GraphQL, for an approved query template that teaches agents exactly how to query, so they stop inventing fields and stop overfetching.PyAgent, for spec-driven orchestration. The agents, the workflow, the budgets, and the contracts between workers are declared in one YAML blueprint and validated before anything runs.Oracle, a Python library for tax-aware portfolio optimization, for the tax math. No model is involved in that step at all.pyagent-trace, which records each step of a run as it happens, worker calls and model calls alike, with the cost of each step attached, so a finished run can be replayed and checked.Last weekend I stitched them together to see whether the combination actually worked once real data started moving through it. The goal was specific: a multi-agent system that rebalances a portfolio for tax efficiency, fetches live market data through GraphQL, and shows a trace of how it reached its recommendation.It worked. It also crashed in ways I did not expect, including a worker that looped on a tool that does not exist. Here is what I built, why each piece is there, and what I would do differently.TL;DR. I built a small multi-agent wealth manager where the model only does what it is good at. A PyAgent blueprint declares the workflow, one fixed GraphQL query fetches the market data, deterministic code does the tax math and the compliance checks, and every run is recorded so it can be replayed step by step. Step through the recorded runs in the live demo: https://me-saurabhkohli.github.io/wealth-agent/ The code is at https://github.com/me-saurabhkohli/wealth-agentOne Blueprint, Four Workers, No Shared NotesPlanning before delegation: the blueprint declares the workers and the stage order before any model is called.Everything the system is, its agents, its workflow, its providers, and its governance, is written down in one YAML file, and that file is checked before a single LLM call is made: dangling references and schema violations fail validation, and contract tests run against a mock model in CI.# blueprint.yaml (trimmed to the parts that matter here)api_version: pyagent/v1metadata: name: wealth-managerproviders: primary: { model: openai:gpt-5.6-sol } small: { model: openai:gpt-5.6-luna }agents: supervisor: { provider: primary } market: { provider: primary } tax: { provider: primary } compliance: { provider: primary } rebalancer: { provider: small }workflows: rebalance: pattern: supervisor agents: lead: supervisor workers: [market, tax, compliance, rebalancer]contracts: market: { output: MarketData } # fixed fields, strict JSON tax: { output: TaxResult } # trades, savings, drift compliance: { output: ComplianceResult } # pass or fail, with reasonsgovernance: token_budget_per_run: 60000 human_checkpoint: before_executionobservability: trace: true cost_tracking: trueOne supervisor agent leads the workflow and delegates each task to specialized workers. Each worker runs in its own context, returns one answer, and ends. Workers do not share memory with each other, and the supervisor works from their returned answers, not from their intermediate steps. Because the workers, the workflow, and the contracts are declared in the manifest rather than hard-coded in the runner, the same manifest can be compiled onto different runtime engines without rewriting the system.The repo is organized like this:wealth_agent/├── blueprint.yaml # Agents, workflow, contracts, budgets, observability├── agents.py # Worker prompts and model bindings├── adapters/│ ├── graphql_client.py # GraphQL endpoint + approved query template│ ├── tax.py # Oracle integration for deterministic tax math│ └── compliance.py # Rule engine for deterministic checks└── pipeline.py # Loads the blueprint, binds adapters, runs a requestThe Python underneath stays thin, because the blueprint carries the structure. pipeline.py loads the blueprint, binds the adapter functions to the names the blueprint declares, and runs one rebalance request:# pipeline.pyblueprint = load_blueprint("blueprint.yaml")runtime = compile_blueprint(blueprint, adapters={ "market.fetch": fetch_market_data, # GraphQL template "tax.optimize": run_tax_optimization, # Oracle "compliance.check": run_compliance_check, # rules engine})result = runtime.run("rebalance", request)The sections below go through each piece in turn, including the ones that broke.First, I Stopped the Agent From Writing Its Own QueriesA fixed query, written down once: the model changes only the tickers, never the query structure.I started with REST. The agent called something like GET /holdings and received a 10KB JSON response: holdings, transaction history, and fields the task never needed. That extra data filled the context window, cost tokens, and made it harder for the model to find the one field it needed. In my runs, that is where the wrong answers started.GraphQL fixed the response size, because the agent asks for named fields and gets only those fields. It created a second problem. Given a complex schema, the model wrote queries with missing required arguments, misused nullable fields, and invented fields that do not exist. I then had to debug the query and the reasoning at the same time.So I stopped asking the model to write the query. The tool carries one approved query template, and the model can change only the $tickers variable:# adapters/graphql_client.pyfrom gql import gql, ClientMARKET_DATA_SKILL = """ SKILL: Fetch market data using this EXACT query. DO NOT modify the query structure. Only change the $tickers variable. query GetMarketData($tickers: [String!]!) { marketData(tickers: $tickers) { ticker price volatility30d sentiment } }"""def fetch_market_data(tickers: str) -> str: """Use the approved GraphQL skill to fetch prices, volatility, and sentiment.""" query = gql(""" query GetMarketData($tickers: [String!]!) { marketData(tickers: $tickers) { ticker price volatility30d sentiment } } """) result = graphql_client.execute(query, variable_values={"tickers": tickers.split(",")}) return str(result)I tested the same market tasks with and without the template. Without it, the agent invented fields such as priceHistory and beta. With it, I recorded zero invented fields in those tests, and token usage dropped by 60 percent, because the responses contained four fields per ticker instead of the full holdings payload.I also wrote the schema down as a contract the endpoint has to honor:# GraphQL Contract (Schema)type MarketData { ticker: String! price: Float! volatility30d: Float! sentiment: Float!}type Query { marketData(tickers: [String!]!): [MarketData!]!}I wrote that contract down in two places: the GraphQL schema, and the blueprint's contract for the market worker's output. A worker reply that does not match the declared shape fails the contract instead of flowing into the supervisor as prose.From then on, a bad request came back as a GraphQL error that named the field, instead of a confident answer built on a field the model had guessed. I spent less time checking whether a response shape was real, because the shape was fixed before the agent ran.The Step the Supervisor Cannot SkipThe first version of this system was prompt driven: a supervisor model with a system prompt that listed the steps and said “You MUST delegate a compliance check before final synthesis.” It planned well. It also skipped steps. Twice, it moved to a final answer without running the compliance check at all, and a stronger prompt rule reduced the slips without eliminating them. Writing the step into the prompt turned out to be only a request to the model, and a request can be skipped.So the order of work moved out of the prompt and into the blueprint. The rebalance workflow declares its stages, and synthesis is the last one. The compliance stage sits between the tax result and the final plan, and the workflow does not reach synthesis without passing through it. There is no instruction left for the supervisor to ignore, because the sequence now lives in the blueprint itself rather than in a prompt the model can drift away from.The supervisor still does the planning and the synthesis itself. Given a request like “Rebalance client ABC123 for tax efficiency, holdings: AAPL 100 @ $150, MSFT 50 @ $300, target 60/40,” it breaks the goal into tasks, delegates the market and tax work in parallel where the workflow allows it, waits for the results, and synthesizes. It cannot reorder the stages, skip one, or call a worker that the blueprint does not declare. Static validation catches a workflow that references a missing agent before any model is called, and the contract tests run the whole shape against a mock model, so a broken spec fails in CI instead of in a live run.The model names are set in one place, in the blueprint's provider block. The first version ran with gpt-4o on the primary provider and gpt-4o-mini for the rebalancer; the blueprint above names their current equivalents, gpt-5.6-sol and gpt-5.6-luChanging the model named in that block changes nothing about the architecture, and none of the results below depend on a specific model, because the steps that need exact answers do not use a model at all.Four Workers, and the Two I Fired the Model FromMarket AgentThis worker fetches current prices and volatility with the GraphQL template above. It is the one worker that still runs a small agent loop, and its tool list has exactly one entry: the approved query. Its prompt requires strict JSON, because earlier versions returned a paragraph about market conditions along with the numbers, and the supervisor then had to parse prose. The blueprint’s contract for this worker says the same thing in a checkable form: the output is a MarketData object, not a paragraph.# agents.py (market worker binding, trimmed)MARKET_AGENT_PROMPT = """ You are a Market Data Specialist. Use fetch_market_data to get prices, 30d volatility, and sentiment. Return a JSON object exactly like this: { "AAPL": {"price": 175.20, "volatility": 0.18, "sentiment": 0.7}, "MSFT": {"price": 420.50, "volatility": 0.15, "sentiment": 0.8} } Round to 2 decimals. No extra text."""# bound in the blueprint to the market agent, with one tool: adapters.fetch_market_dataEven with that prompt, the model sometimes added a greeting before the JSON. I added a regex fallback that extracts the first JSON object from the reply. That fallback should not have been necessary. The prompt already ended with the words 'No extra text,' and the model still opened some replies with a greeting, so the regex stayed. The contract check behind it catches what the regex cannot: a reply with no valid JSON object in it fails the stage instead of reaching the supervisor.Tax AgentTax math belongs with documents and a calculator: Oracle computes it, the model only formats the input.This worker started as an LLM doing math, and that version failed on basic work. It calculated simple gain and loss incorrectly, and it could not keep cost basis straight across multiple lots in the same position. I removed the model from the calculation.The tax logic now runs in Oracle, a Python library for tax-aware portfolio optimization. The model’s only role in this step is formatting the input. Oracle computes the result, and the worker returns it as JSON for the supervisor:# adapters/tax.pyimport pandas as pdimport jsonfrom service.oracle import Oraclefrom service.oracle_strategy import OracleStrategyfrom service.helpers.enums import OracleOptimizationTypedef run_tax_optimization(holdings_json: str) -> str: holdings = json.loads(holdings_json) targets = {"targets": [ {"asset_class": "stock", "target_pct": 0.6}, {"asset_class": "bond", "target_pct": 0.4} ]} tax_lots_data = [] # ... populate tax_lots_data from holdings ... tax_lots_df = pd.DataFrame(tax_lots_data) prices_df = pd.DataFrame(...) # from holdings strategy = OracleStrategy(..., optimization_type=OracleOptimizationType.TAX_AWARE) oracle = Oracle(strategy=strategy) result = oracle.optimize() return json.dumps({ "recommended_trades": result.trades.to_dict("records"), "tax_savings_estimate": result.tax_savings, "drift_reduction": result.drift_reduction })After that change, the tax step stopped producing arithmetic errors in my runs, because Oracle was doing every calculation and the model was only formatting its input. The output also became repeatable: the same lots and prices produced the same trades, which made the traces useful for comparison instead of just recording.Compliance AgentCompliance had the same problem in a different form. Checking a concentration limit or a wash sale window is a set of fixed rules applied to dates and quantities. When I left it to the model, the checks were inconsistent between runs on the same trades.I replaced it with simple-rule-engine in a plain Python function. The wash sale check uses Oracle’s precomputed conflict list instead of asking a model to reason about dates:# adapters/compliance.pyfrom simpleruleengine.ruleset.rule_set_decision import RuleSetDecisionimport jsondef run_compliance_check(proposed_trades_json: str) -> str: trades = json.loads(proposed_trades_json) # ... setup facts ... concentration_rule = RuleRowDecision(...) ruleset = RuleSetDecision(concentration_rule, ...) result = ruleset.evaluate(fact) return resultMoving tax and compliance to code saved an estimated $0.02 per run in model calls. The more useful change was what it did to checking the work afterward. A pass or fail from the rules engine can be reproduced from the inputs. When a model produces the pass or fail instead, the only way to check it is to keep the trace and rerun it.Rebalancer AgentThis one is close to a placeholder, and I am leaving that in because it is true of the experiment. Oracle and the Market Agent produce the substance. The Rebalancer takes their JSON outputs and writes the version a person reads: “Sell 20 shares of AAPL to reduce your stock exposure to 60 percent. This will generate a small capital gain of about $500.”It runs on the small provider in the blueprint, with no tools at all:# agents.py (rebalancer binding, trimmed)REBALANCER_AGENT_PROMPT = """ You are a Portfolio Rebalancing Specialist. Synthesize the outputs into a clear plan.Inputs: tax_optimization_result, market_data, compliance_status.Output: plain-English summary with current snapshot, recommended trades, tax impact, compliance note. Keep it concise."""# bound in the blueprint to the rebalancer agent on the small provider, tools: noneI kept the split because it follows what each side was actually good at. The model is good at turning three JSON documents into a readable paragraph. Producing the numbers inside those documents is where it kept failing, on tax lots and on compliance checks, so those calculations now happen before the documents reach it.Every Run, Recorded Step by StepA multi-agent run gives you a final answer and, without tracing, very little else. When an early version of this system recommended selling MSFT at a loss that was actually a gain, I had the recommendation in front of me and no record of which step had produced the wrong sign. I could rerun it, but a rerun is a different run.Reading a run back, step by step: the replay is where the wrong step in a failed run actually shows up.That failure is why observability is a section of the blueprint instead of a wrapper I bolted on later. With tracing declared, every run publishes its steps to a trace event bus: each model call, each adapter call, and each worker's result, in order, with the token cost attached to the step that spent it. The events export as JSONL, and the studio view replays a recorded run step by step. When a number in the final plan looks wrong, I can open the trace and find the step that produced it, instead of rerunning the system and hoping the same failure happens again.# pipeline.py (tracing is declared in the blueprint; this is what consumes it)from pyagent_trace import TraceEventBus, JsonlExporter, CostTrackerbus = TraceEventBus()bus.subscribe(JsonlExporter("runs/rebalance.jsonl"))bus.subscribe(CostTracker())runtime = compile_blueprint(blueprint, adapters=ADAPTERS, trace_bus=bus)With a full run recorded, one view showed the supervisor’s plan, the Market Agent’s GraphQL call, Oracle’s tax lot calculation, and the compliance evaluation in sequence. The cost tracker also settled an argument with myself: the two workers I moved to code were not just more reliable, they were the ones whose per-run cost went to zero, because there was no model call left in them to pay for.What Broke: A Looping Worker, a Rate Limit, and a Skipped ChecklistThe other half of the experiment: a looping worker, a rate limit, and a supervisor that skipped its own list.Sub-agents never returning. In an early version, the Market Agent looped on a tool that does not exist and kept spending tokens. The blueprint now carries a token budget per run, workers run under bounded execution, and each worker has to end with an explicit FINAL ANSWER line. A worker that hits the budget stops, and the trace shows where the money went.GraphQL rate limiting. The supervisor’s parallel calls hit the endpoint at the same time. A Semaphore(5) limiting requests per step fixed it.Supervisor ignoring its checklist. Covered above, and worth repeating in the failure list because it was the most dangerous one: the system produced a confident final plan with the compliance check never run. A prompt rule made the skips rarer. Declaring the stage order in the blueprint took the decision away from the model, and that is the version of the fix I trust.Oracle setup friction. Installing the CBC solver took a few tries. On a Mac, brew install coin-or-tools/coinor/cbc was the command that worked.Rules engine learning curve. simple-rule-engine does what I needed, and its documentation is sparse. The first rule took about an hour. The rest were faster once that one worked. Next time I would compare Zen Engine and Arta first, mainly for documentation and a visual editor.What I Would Do With Another WeekendKeep the human checkpoint where the blueprint already declares it, before execution, and test it properly, so no trade plan leaves the system without a person reading it.Cache GraphQL responses in Redis. The Market Agent asked for the same tickers more than once in a single run.Move the compliance rules to Zen Engine, for JSON decision models and a visual editor I can show a non-engineer.Use the blueprint’s recovery policies for a single worker failure. In the current version, one failed worker still ends the whole rebalancing run, even though the spec has a place to declare what should happen instead.If these workers ever move into separate services or come from different vendors, I would also put the tool calls behind MCP and the agent-to-agent handoffs behind A2A. Inside one Python process, direct function calls are simpler and they were not the source of any failure I recorded.The Scorecard: What the Model Kept, and What It LostWhat the experiment produced was a supervisor that coordinates three kinds of work, not a portfolio manager. The results differed sharply by kind, and the pattern across them is the useful part.Work the model did well: breaking a goal into tasks, delegating them, and writing the final explanation.Work the model did badly, measured in my runs: arithmetic on tax lots, where it got basic gain and loss wrong; compliance checks, where the same trades did not always get the same answer; and free-form GraphQL, where it invented fields such as priceHistory and beta.Work that improved when the model was removed from it: tax optimization, which became repeatable once Oracle computed it; compliance, which became a reproducible pass or fail; and market data, which used 60 percent fewer tokens once the query was fixed and only the tickers changed.Work that improved when it moved out of the prompt and into the spec: the order of the stages, which a prompt rule could not hold and a declared workflow does.If you want to try this yourself, clone the repo, add your own API keys, and run the same test I did: one run with the model writing its own GraphQL, and one with the fixed template. Then open the trace for the run that fails and find the exact call where it went wrong. In my own traces, the call where things went wrong was rarely the one I had suspected before opening them.If you enjoyed this, please clap and follow me on Medium for more experiments in AI agents, spec-driven workflows, and front-end engineering.And if you’re a gym’er, then let the clap sound be loud: hold the button with all your power :)P.S. All the code from this experiment is in a GitHub repo here: https://github.com/me-saurabhkohli/wealth-agent. Run it, break it, and tell me what you built.P.P.S. Do not deploy this with real money. I am not a financial advisor, and neither is your LLM.Spec-Driven AI Wealth Manager was originally published in Towards AI on Medium, where people are continuing the conversation by highlighting and responding to this story.