AI strategy generation pipeline
TodoAI's AI is not "one black-box call". It runs in two stages: first outputs an English reasoning chain, showing each step of the thinking; then compiles that reasoning into executable DSL rules.

Why two stages?
Single-stage LLM-generated strategies have three common problems:
- Unexplainable — the user doesn't know why the AI picked RSI(14) over RSI(21)
- Hard to iterate — adjusting one number requires regenerating the whole thing
- Easily derailed — LLMs often skip details the user didn't explicitly state (stop-loss, symbol, timeframe)
Two stages separate "thinking" from "implementation": readable thinking → editable reasoning → regenerated DSL.
Stage 1: Reasoning chain
File: src/lib/ai-reasoning-service.ts
Input: a natural language description of the user's idea
Processing:
- SSE streamed, each step is pushed to the frontend immediately
- 60s timeout per request (prevents the LLM from hanging the request)
- 1 automatic retry; on main model failure, falls back to
AI_FALLBACK_MODEL - All steps batch-persisted to
StrategyEventLog(stepType='REASONING')
Output: ReasoningStep[], each step contains:
stepType: 'TRADE' | 'REASONING' | 'SYSTEM'reasoning: English textcauseStepId: the prior step's id this depends on (supports causal-chain display)
Stage 2: DSL compilation
File: src/lib/ai-service-stream.ts
Input: the complete reasoning chain from Stage 1
Processing:
- Feeds the reasoning chain back to the same LLM, with a prompt emphasizing "based on the above reasoning, generate executable rules"
- Outputs strict JSON structure (CustomStrategy)
- When LLM occasionally emits non-strict JSON, the
src/app/api/strategy/fix-jsonendpoint salvages it
Output: a Partial with buyRules/sellRules/indicators/stopLoss/takeProfit
Stage 3: Zod validation
File: src/lib/strategy-validator.ts
Validates:
- RuleNode tree structure is valid (correct AND/OR nesting)
- Indicator parameters in range (RSI period ∈ [2, 100])
- SL/TP percentages in a sensible range
- All references are closed
Validation failure → refuse to write; frontend shows "AI generated invalid JSON, please retry".
Validation pass → write to MongoDB (Strategy model) → render in DslEditor.
Reasoning chain visualization
The frontend renders the reasoning chain in both AiStrategyGenerator and StrategyTerminal:
- Timeline view (
ReasoningTimeline): each step is a node showing stepType label and text - DSL bidirectional link: click a step's "corresponding DSL line" button, DslEditor auto-scrolls to that line and selects it
- Human-in-the-loop editing: users can edit a step's content, click "regenerate based on this", and Stage 2 re-generates the DSL from the modified reasoning
Reverse link (dslLine field)
Each StrategyEventLog can store dslLine (integer, 1-based), indicating which line of the DSL this reasoning step ultimately influenced.
src/lib/reasoning-dsl-linker.ts runs a fuzzy match after DSL generation: it extracts indicator names from the step text (RSI/MACD/BB/...) and scores each DSL line by token overlap, picking the most matching line.
This way the UI can "click a reasoning step to jump to the corresponding DSL line".
Model configuration
| Variable | Purpose | Default |
|---|---|---|
API_URL | OpenAI-compatible endpoint | https://api.siliconflow.cn/v1/chat/completions |
AI_MODEL_NAME | Main model | Pro/deepseek-ai/DeepSeek-V3 |
AI_FALLBACK_MODEL | Fallback when main fails | deepseek-ai/DeepSeek-V4-Flash |
AI_LLM_TIMEOUT_MS | Per-call timeout | 60_000 (60s) |
AI_LLM_MAX_RETRIES | Retry count | 2 |
Any OpenAI-compatible endpoint works — SiliconFlow, QiniuYun, OpenAI, Azure OpenAI.
Known limitations
- Fuzzy matching is heuristic (token overlap), not semantic alignment. LLM-explicit annotation is the next step
- The reasoning chain is linear (array), no explicit causal arrows (causeStepId is stored but not yet rendered)
- Editing reasoning then regenerating only works for existing strategyId; the initial-create flow's "reasoning first, then store" isn't wired yet