Fast Decision Models (self.agents.decide)

Use self.agents.decide(...) when your strategy needs a fast, typed decision over evidence you already fetched (prices, indicators, headlines, JSON snapshots, or chart images) without running a multi-turn tool-calling agent loop.

Decision models evaluate shared multimodal evidence against typed predicate, choice, and score questions in a single forward pass with zero output tokens, and integrate automatically with LumiBot’s AgentReplayCache for deterministic sub-millisecond backtest replay.

What BotSpot MCP adds

Use Claude, ChatGPT, Codex, Cursor, VS Code or another MCP-compatible assistant? Connect the free BotSpot MCP for:

  • Skills: build LumiBot strategies.

  • Free data: news, economics and SEC filings.

  • Backtests: run tests and read charts.

  • Cloud hosting: low-cost scheduled bots.

  • Community: share bots and discuss trades.

  • Marketplace: discover and publish strategies.

  • Broker linking: connect accounts through BotSpot.

Connect your AI assistant

When to use decide() vs. run()

Choosing between fast decision models and full agents

Dimension

self.agents.decide(...)

self.agents["name"].run(...)

Execution shape

Single forward pass, zero output tokens

Multi-turn reasoning loop with built-in, custom, and MCP tools

Best use cases

Fast entry/exit gates, news/filing triage, chart pattern scoring, multi-symbol screening

Open-ended market discovery, SEC/FRED/web research, multi-leg option selection, direct order execution

Output type

Typed DecisionResult (probability(), choice(), score())

AgentRunResult (summary, text, tool traces, optional output_schema)

Backtest replay

Automatic AgentReplayCache (sub-millisecond warm replay)

Automatic AgentReplayCache

Combine both in a hybrid strategy: run self.agents.decide() on every bar as a low-latency filter, and wake a full research or trading agent with self.agents["trader"].run(...) only when the decision crosses your threshold.

Supported Providers and Authentication

LumiBot routes self.agents.decide(model=...) automatically from the model ID:

  • OpenAI Decisions API (model="gpt-6-luna" or "openai/gpt-6-luna"): calls POST /v1/decisions (default base https://api.openai.com, overridable via OPENAI_BASE_URL or base_url). Authenticate with OPENAI_API_KEY or explicit api_key=....

  • Google Gemini Decisions API (model="gemini-decision-1" or "google/gemini-decision-1" or "models/gemini-decision-1"): calls POST /v1beta/decisions (default base https://generativelanguage.googleapis.com, overridable via base_url). Authenticate with GOOGLE_API_KEY, GEMINI_API_KEY, or explicit api_key=....

  • Managed BotSpot AI Gateway: when no personal BYOK key or custom base_url is supplied and BOTSPOT_AI_GATEWAY_URL and BOTSPOT_AI_GATEWAY_TOKEN are set, LumiBot automatically routes both OpenAI and Gemini decision requests through the managed /v1/decisions endpoint.

Method Signature

result = self.agents.decide(
    model="openai/gpt-6-luna",          # or "google/gemini-decision-1"
    evidence=...,                        # str, JSON dict/list, messages, or multimodal dict
    questions=...,                       # list[dict] or dict[name, spec]
    timeout_seconds=15.0,                # HTTP request timeout
    cache=None,                          # None = auto-enabled in backtests, False in live
    replay_scope=None,                   # optional cache namespace string
    api_key=None,                        # optional explicit API key override
    base_url=None,                       # optional provider base URL override
    prompt_cache_key=None,               # optional OpenAI prompt cache key
)

Evidence Shapes

evidence can be passed in any of five normalized formats:

  1. Plain text (str): e.g. a headline, filing excerpt, or market brief.

  2. Structured JSON (dict or list): serialized cleanly into the provider’s structured input format.

  3. Multimodal shorthand dict: any subset of {"text": str, "json": Any, "image": ..., "images": [...]}. Each image can be a pathlib.Path, raw bytes, a data:image/...;base64,... URI, an HTTPS URL, or a dict with image_url / bytes / path.

  4. Explicit input parts list: list of {"type": "input_text", "text": ...}, {"type": "input_json", "data": ...}, and {"type": "input_image", ...}.

  5. Chat messages list: list of {"role": ..., "content": ...} objects.

Question Types

Pass questions either as a list of dicts (each with a unique name) or as a dict mapping name -> spec:

  • predicate (aliases: noul, boolean, bool, yes_no): returns a calibrated probability in [0.0, 1.0] and a boolean value (probability >= 0.5). Read with result.probability("name").

  • choice: selects one option from choices (or criteria) and returns per-choice probabilities. Read with result.choice("name") and result["name"].probabilities.

  • score: scores the evidence against a rubric and returns a numeric score plus optional level probabilities. Read with result.score("name").

Each question spec requires type and instructions (or its alias prompt).

Typed Return Objects

self.agents.decide(...) returns a DecisionResult containing a mapping of name -> DecisionAnswer (both exported from lumibot.components.agents):

  • DecisionResult attributes: model, provider, answers, usage, cache_hit, cache_key, latency_ms, raw.

  • DecisionResult helpers: result["name"], result.get("name"), result.probability("name"), result.choice("name"), result.score("name"), result.to_dict(), DecisionResult.from_dict(...).

  • DecisionAnswer attributes: name, type ("predicate", "choice", "score", or "refusal"), value, probability, choice, score, probabilities, confidence, refused, refusal_reason, raw.

Runnable Example: OpenAI Decisions (gpt-6-luna)

This strategy computes a fast Python market snapshot on each bar, calls OpenAI’s Decisions API for a calibrated long/flat gate and conviction score, and lets Python own position sizing and order execution:

from datetime import datetime
from lumibot.backtesting import YahooDataBacktesting
from lumibot.strategies import Strategy


class FastDecisionMomentumStrategy(Strategy):
    parameters = {
        "symbol": "SPY",
        "min_bull_prob": 0.65,
        "min_score": 7.0,
    }

    def initialize(self):
        self.sleeptime = "1D"

    def on_trading_iteration(self):
        symbol = self.parameters["symbol"]
        bars = self.get_historical_prices(symbol, 20, "day")
        if bars is None or bars.df.empty:
            return

        closes = bars.df["close"].tolist()
        evidence = {
            "as_of": self.get_datetime().isoformat(),
            "symbol": symbol,
            "last_close": round(closes[-1], 2),
            "return_5d_pct": round((closes[-1] / closes[-6] - 1.0) * 100, 2) if len(closes) >= 6 else None,
            "return_20d_pct": round((closes[-1] / closes[0] - 1.0) * 100, 2),
        }

        decision = self.agents.decide(
            model="openai/gpt-6-luna",
            evidence=evidence,
            questions={
                "trend_bullish": {
                    "type": "predicate",
                    "instructions": "Is the 20-day and 5-day price action constructive for a long entry?",
                },
                "action": {
                    "type": "choice",
                    "instructions": "Select the best portfolio action given this snapshot.",
                    "choices": ["enter_long", "hold_flat"],
                },
                "conviction": {
                    "type": "score",
                    "instructions": "Rate setup quality from 1 (weak) to 10 (strong).",
                },
            },
        )

        bull_prob = decision.probability("trend_bullish")
        action = decision.choice("action")
        conviction = decision.score("conviction")
        pos = self.get_position(symbol)

        if (
            action == "enter_long"
            and bull_prob >= self.parameters["min_bull_prob"]
            and conviction >= self.parameters["min_score"]
            and pos is None
        ):
            price = self.get_last_price(symbol)
            qty = int((self.cash * 0.90) // price) if price else 0
            if qty > 0:
                self.submit_order(self.create_order(symbol, qty, "buy"))
        elif action == "hold_flat" and pos is not None:
            self.close_position(symbol)


if __name__ == "__main__":
    FastDecisionMomentumStrategy.backtest(
        YahooDataBacktesting,
        datetime(2026, 1, 2),
        datetime(2026, 3, 31),
    )

Runnable Example: Google Gemini Multimodal Decisions (gemini-decision-1)

You can pass a chart screenshot alongside structured JSON telemetry to Google Gemini’s /v1beta/decisions endpoint:

from pathlib import Path
from lumibot.strategies import Strategy


class ChartDecisionStrategy(Strategy):
    def initialize(self):
        self.sleeptime = "1D"

    def on_trading_iteration(self):
        chart_path = Path("latest_chart.png")  # or bytes / data URI
        result = self.agents.decide(
            model="google/gemini-decision-1",
            evidence={
                "text": f"Daily review for BTC/USD at {self.get_datetime().isoformat()}",
                "json": {
                    "rsi_14": self.indicators.rsi("BTC", length=14),
                    "position_open": self.get_position("BTC") is not None,
                },
                "image": chart_path,
            },
            questions=[
                {
                    "name": "breakout_confirmed",
                    "type": "predicate",
                    "instructions": "Does the chart show a clean breakout above resistance with rising momentum?",
                },
                {
                    "name": "regime",
                    "type": "choice",
                    "instructions": "Classify the current market regime.",
                    "choices": {
                        "trending_up": "Higher highs and higher lows",
                        "range_bound": "Sideways consolidation",
                        "trending_down": "Lower highs and lower lows",
                    },
                },
            ],
        )
        self.log_message(
            f"breakout_prob={result.probability('breakout_confirmed'):.2f}, "
            f"regime={result.choice('regime')}, cache_hit={result.cache_hit}"
        )

Deterministic Backtest Replay

During backtests, cache=None (the default) automatically caches every self.agents.decide() call in AgentReplayCache unless LUMIBOT_AGENT_REPLAY_CACHE=0. Cache keys cover the provider, model, normalized evidence, normalized questions, and optional replay_scope. Warm backtest reruns return the cached DecisionResult with cache_hit=True and latency_ms=0 at zero model cost.

In live trading, cache=None disables caching so every live bar queries the provider fresh. Pass cache=True or cache=False to override explicitly.

Frequently asked questions

When should I use self.agents.decide() instead of a full agent?

Use self.agents.decide() whenever your Python code already has the evidence (bars, indicators, headlines, quotes, or a chart image) and only needs fast probabilities, categorical choices, or rubric scores. Use self.agents["name"].run() when the model needs to search, call tools, read documents, or execute orders on its own.

Does self.agents.decide() place broker orders?

No. Decision models are strictly read-only single-pass evaluators. Your Python code inspects the typed DecisionResult and decides whether to submit orders through self.submit_order(...) or wake a trading agent.

How does caching work in backtests vs. live trading?

In backtests, self.agents.decide() caches results automatically in AgentReplayCache so repeated runs with identical evidence replay instantly with zero API cost. In live trading, caching is off by default so every bar gets a fresh model decision.

Can I pass images or JSON dicts as evidence?

Yes. Pass evidence={"text": ..., "json": ..., "image": Path("chart.png")} (or "images": [...] with Path, raw bytes, data URIs, or URLs). LumiBot normalizes the payload for both OpenAI /v1/decisions and Google Gemini /v1beta/decisions.