LLM Configuration Guide
Platform boundary (2026-11-08): Gemini API and Vertex AI have different model lifecycles. The Vertex AI
gemini-3.6-flashplaceholder is an input example; Google Cloud documents retirement on 2026-11-19 for that platform. Confirm model availability for your project and region; Gemini API validation does not validate Vertex AI. A DeepSeek key alone infersdeepseek/deepseek-v4-flash; explicit models and higher-priority configuration still take precedence.
Welcome! Whether you are a beginner newly exposed to AI or a veteran skilled with various APIs, this guide will help you set up Large Language Models (LLMs) quickly.
This project exposes a unified AI model access flow that supports official APIs, OpenAI-compatible platforms, and local models. Under the hood it is powered by LiteLLM, but most users only need to think in terms of picking a provider, adding an API key, and optionally choosing a primary model or channels. To cater to different experience levels, we provide a three-tier configuration hierarchy. Choose the method that fits you best.
If you are choosing a concrete provider, setting up GitHub Actions Secrets / Variables, troubleshooting a details.reason error, or rolling back an LLM configuration, start with the Provider Configuration Guide. It is the maintained reference for provider presets, Actions variable mapping, runtime capability-check boundaries, and common error handling.
Quick Navigation: Which section should you read?
Section titled “Quick Navigation: Which section should you read?”- [Beginners] “I just want to get the system running ASAP, keep it as simple as possible!” -> Go to Method 1: Simple Model Config
- [Advanced Users] “I have several Keys, want to configure fallback models, and define custom Base URLs.” -> Go to Method 2: Channels Mode Config
- [Veterans] “I want complex load balancing, request routing, and enterprise-level high availability!” -> Go to Method 3: Advanced YAML Config
- [Local Models] “I want to use Ollama local models!” -> Go to Example 4: Using Ollama Local Models
- [Vision Models] “I want to extract stock codes from images!” -> Go to Vision Model Config
Generation Backend (Phase 4)
Section titled “Generation Backend (Phase 4)”The generation backend is the outer runtime selector for regular stock analysis, market review, and generate_text(). The default remains litellm with zero regression. codex_cli / claude_code_cli / opencode_cli are explicit opt-in local CLI backends and are currently experimental/limited.
GENERATION_BACKEND=litellmGENERATION_FALLBACK_BACKEND=litellmGENERATION_BACKEND_TIMEOUT_SECONDS=300GENERATION_BACKEND_MAX_OUTPUT_BYTES=1048576GENERATION_BACKEND_MAX_CONCURRENCY=1LOCAL_CLI_BACKEND_MAX_CONCURRENCY=1# Optional: leave empty to use the local OpenCode default model; set it only to pass a --model override.# OPENCODE_CLI_MODEL=provider/modelAGENT_BACKEND=autoAGENT_GENERATION_BACKEND=autoGENERATION_BACKEND=litellm|codex_cli|claude_code_cli|opencode_cli. Local CLI backends are generation backends, not LiteLLM providers; do not setLITELLM_MODEL=codex_cli/...,LITELLM_MODEL=claude_code_cli/..., orLITELLM_MODEL=opencode_cli/....- With
GENERATION_BACKEND=opencode_cli, DSA does not pass--modelby default and lets local OpenCode use its own default model configuration.OPENCODE_CLI_MODELis only an optional override; when set, DSA passes it as one OpenCode--modelargument. Provider authentication, account state, and model availability are handled by your local OpenCode setup. - If
GENERATION_FALLBACK_BACKENDis unset, it defaults tolitellm. In local.env, an explicit empty value disables backend-level fallback. A fallback equal to the primary backend is treated as no-op. The bundled GitHub Actions workflow explicitly exportslitellmwhen this variable is not configured; to disable backend fallback there, set the fallback to the primary backend, for exampleGENERATION_BACKEND=codex_cli+GENERATION_FALLBACK_BACKEND=codex_cli. - With
GENERATION_BACKEND=codex_cli|claude_code_cli, regular analysis and market review do not require Gemini/OpenAI/Anthropic/DeepSeek API keys. If the corresponding executable is missing, DSA returns structuredcommand_not_foundinstead of “API key not configured”. - The current
codex_clipreset usescodex --ask-for-approval never exec --sandbox read-only --output-last-message <temp-file> -. Regular analysis is unattended generation, soneverprevents a non-interactive run from stopping for human approval whileread-onlyretains the filesystem boundary. DSA reads the final response from the temporary file; the duplicate response printed to stdout is removed from diagnostics previews and output-size accounting and is never used for main-analysis JSON parsing. Official references: Codex non-interactive mode and Codex CLI command line options. This repository has live-verifiedcodex-cli 0.144.3and does not claim a wider minimum version range; if the installed CLI does not support a preset argument, DSA returns structuredcapability_unsupported/cli_contract_unsupporteddiagnostics and falls back tolitellmwhen backend fallback is configured. - The current
claude_code_clipreset usesclaude --safe-mode --tools "" --disallowedTools "mcp__*" --strict-mcp-config --no-session-persistence --output-format json -p <static instruction>, with the full DSA prompt passed through stdin. DSA only extracts the final text from Claude’sresult/successJSON envelope. If--json-schemais enabled later, schema mode must extractstructured_output, and the output still goes through DSA’s existing JSON validator, minimal parser contract,_parse_response(), integrity retry, placeholder fill, and usage telemetry. The CLI flags are based on the Claude Code CLI reference. This PR smoke-testedclaude 2.1.177 (Claude Code)and does not claim a wider minimum version range. - The current
opencode_clipreset usesopencode --pure run --format json [--model <OPENCODE_CLI_MODEL>] <static instruction> --file <temp prompt file>. DSA only appends--modelwhenOPENCODE_CLI_MODELis explicitly set. The full DSA prompt is written to a permission-restricted temporary file and is not placed in argv. DSA only extracts text from OpenCode JSON event output that has no tool events and ends with a normalstep_finish;tool_use,error,question, orpermissionevents fail structurally. The CLI flags are based on the OpenCode CLI reference, and project config merge semantics are documented in the OpenCode config reference. This PR smoke-testedopencode 1.17.11and does not claim a wider minimum version range. - Local CLI backends do not support streaming. Stream requests degrade to non-stream and do not return
capability_unsupported. - Local CLI usage is normally unavailable. DSA does not persist fake 0-token, fake cost, or fake cache telemetry.
- Local CLI execution has hard caps:
GENERATION_BACKEND_TIMEOUT_SECONDSmax3600,GENERATION_BACKEND_MAX_OUTPUT_BYTESmax33554432,GENERATION_BACKEND_MAX_CONCURRENCYmax16, andLOCAL_CLI_BACKEND_MAX_CONCURRENCYmax4. Diagnostic stdout/stderr plus the final response are counted together; for--output-last-messagepresets, the final response duplicated to stdout is not counted twice and is not exposed instdout_preview. - Local CLI
stdout_preview/stderr_previewredact short credential assignments before diagnostics are emitted, regardless of value length. Uppercase environment assignments reuse the child-env fail-closed sensitive-name contract; scalar assignments in JSON, YAML, and ordinary logs use a narrower credential-field allowlist; URLs keep separate userinfo, webhook, and sensitive-parameter rules. Ordinary troubleshooting fields such astoken_budget,session_id, andsort_keyare not removed merely because their names containtoken,session, orkey; however, an unquoted sensitive YAML scalar has no reliable same-line boundary, so redaction fails closed from that value through the end of the line and does not preserve later fields on that line. - Local CLI default concurrency is 1. Effective local CLI concurrency is
min(LOCAL_CLI_BACKEND_MAX_CONCURRENCY, GENERATION_BACKEND_MAX_CONCURRENCY)and does not inheritMAX_WORKERS. AGENT_GENERATION_BACKEND=autodoes not inherit local CLI values fromGENERATION_BACKEND; Agent tool calling remains on LiteLLM. The Web settings page only exposesauto|litellm; a hand-writtenAGENT_GENERATION_BACKEND=codex_cli|claude_code_cli|opencode_clidoes not enable Agent text-only mode and returns an explicit unsupported tool-calling diagnostic.- The Phase 6a DSA Tool Surface retains tool-schema, permission, scope-guard, structured-error, audit, and redaction support. Default LiteLLM keeps its existing registry/runner tool path; removing the runtime does not rewire tool execution.
codex_cli/claude_code_cli/opencode_cliremain generation-only and are never Agent tool fallbacks. - The Web settings generation-backend quick check only reads saved
.env, runtime defaults, and unsaved drafts. It does not write config, reload runtime, or send a real model request;availableonly means the current config can be attempted. JSON smoke test is a separate explicit button that sends one real generation-backend request with a server-owned fixed JSON prompt/schema to verify extractor behavior, JSON contract, timeout, output limits, and usage-unavailable semantics. GET /api/v1/system/config/generation-backends/statusonly reads saved config. Unsaved drafts usePOST /api/v1/system/config/generation-backends/status/previeworPOST /api/v1/system/config/generation-backends/smoke-test; masked secrets preserve saved values.health_statusandlast_error_code/messagedescribe only the current computation, not persisted historical health.
Chat Session State And Upgrades
Section titled “Chat Session State And Upgrades”The server owns the main discussion object and saved Skills. LiteLLM single/existing multi consume the same accepted snapshot. Omitted/null Skills inherit saved choices (configuration defaults when unset); explicit [] saves a cleared selection and uses built-in defaults, not a non-empty configured selection. Only unique server-index names establish identity. Comparisons do not switch the main object; execution failure/stopping does not undo acceptance. On a state/instance conflict, refresh and retry manually; Web keeps the input and draft selection and does not resend automatically.
Legacy recovery uses explicit codes, not historical names. Analyze 600519 → switch to CATL by name → risks? requires confirmation rather than reusing 600519. Startup adds state columns without deleting messages, Skills or reports. Stop the backend before upgrading/rolling back; use SQLite backup or a complete stopped-server backup, not a main-file-only copy with active WAL. Keep configuration, database location and data directory; update matching backend/Web and restart without deleting tables/columns. Rollback preserves added columns and old-code message/Skill writes. Re-upgrade after intervening user messages shows an unconfirmed object until explicitly reconfirmed. Concurrent old/new writers are unsupported. For separate deployments, upgrade backend before Web and roll back Web before backend.
Comparisons that mix codes and names include both identities. An adjacent explicit code disambiguates a matching listing name (for example, 688981中芯国际). 从600519改看300750 / 把600519换成300750 bind the destination to the switch operation: the destination remains 300750 even if it is already current or the instruction is repeated. Each acceptance still saves the message and increments the version. Explicit switching permits only the new object’s tool scope and removes mismatched report hints. Multiple destination alternatives require clarification; neither the last mention nor exclusion of the current object selects the destination.
With a confirmed object, 看看近期走势 / 分析一下财务状况 / 分析风险 continue analysis while preserving confirmation source and time. 分析300750 or a uniquely matched name can still confirm a new object. An analysis verb followed by arbitrary prose is not evidence of switching; an explicit but unconfirmed 改看… requires clarification without analysis execution. Legacy history shares direction/action rules but establishes facts only from valid explicit codes: ordinary follow-ups preserve a candidate, an unconfirmed new switch invalidates it, and later follow-ups cannot revive it; a later explicit code can establish a new fact. Historical names provide change evidence only, never a new confirmation fact. Reading recovered state does not persist the object or increment the version.
Negated, questioned, conditional or quoted switches do not confirm a target: 不要改看300750,继续分析600519 maintains 600519; 是否改看300750? preserves the object and asks for clarification without permitting 300750. Codes and names use actual occurrence positions. Legacy confirmation requires a valid code at the destination itself, not an equal code elsewhere in the sentence. A standalone valid code/unique name remains supported; a lone incidental mention in arbitrary prose does not automatically confirm it.
An adjacent conditional antecedent/consequent such as 如果600519下跌,就改看300750 remains conditional across the comma: save the question and clarify without switching or starting analysis. Legacy recovery does not treat it as a new confirmation either. Negated strong, weak and choice comparisons contribute no participants; 不要研究600519和300750的区别,继续分析600519 still analyzes 600519 with only that stock in scope. Independent affirmative clauses are not disabled by a condition or negation elsewhere in the message.
The ask-stock backtest tool uses the guard-validated market identity for its summary, recent rows, count and pagination. Valid prefix/suffix aliases and the current CN writer’s numeric storage keys remain readable, without bare-code index-based market discovery. Numeric keys are generated only from validated SH/SZ/BJ targets using the existing writer normalization. Numeric details require a same-object analysis source, with no contrary persisted market. Numeric rollups require same-object results in their evaluation-window/engine bucket and no conflicting numeric source; unprovable ownership returns normal no-data information. Normal legacy CN sources without a market field retain the existing bare-code storage convention: numeric keys are not categorically excluded. Service/repository callers without a strict target keep legacy behavior; no historical data is migrated. This internal target seam supports the tool’s existing summary/recent reads, not date/phase dynamic aggregation: unsupported combinations fail explicitly rather than dropping identity constraints.
Incidental mentions in ordinary follow-ups do not expand tool scope. Existing strict Chat stock tools share identity, scope and applicability checks, then carry that call’s validated target into cache/provider routing. Daily history, technical analysis and realtime quotes distinguish stocks from indices; cache misses do not fetch a colliding stock. Loss of required identity evidence before execution rejects only the affected object, not independently valid scope members. A validated call does not reclassify through a later registry read. Chip, company information, capital-flow and per-stock backtest tools explicitly reject indices; existing market/ETF restrictions remain. A strict custom tool without an applicability declaration rejects only that call. News queries use the confirmed identity/name, not another stock name guessed by the model.
Current Bot and Web may alternate within the same session instance. After Web confirms an object, an ordinary Bot follow-up uses its strict tool scope; a valid comparison adds participants only for that turn. Both preserve the Web main object, confirmation source/time and state version. Bot does not independently persist a new main object: an explicit switch or an unsafe continuation leaves Web pending reconfirmation rather than claiming the old object remains reliable. Unknown user writes from genuinely old/rollback code still require reconfirmation and are not treated as current state-aware Bot turns. Current Bot commits check the prepared generation, version and latest user anchor; a newer acceptance rejects the stale commit without appending its question or automatically retrying the model. Replies, provider traces and summaries remain bound to the captured instance and actual message source. Delete/recreate rejects late writes from the old instance. A late initial Web list may update presentation but cannot clear a new request/accepted instance or cancel its stream; ordinary missing-session restoration, switching and creation retain their existing behavior.
The session-state contract does not change model routing or Phase 2 generation-only capabilities. The Codex App Server Chat backend has been removed; there is no execution entry point awaiting Gate approval. Historical Gate 0B BLOCKED records do not become passes as a result; controlled execution tests do not establish real-runtime safety or upgrades on every platform.
Codex App Server Chat Retirement
Section titled “Codex App Server Chat Retirement”The Codex App Server Chat backend has been removed. AGENT_BACKEND supports only auto (recommended, keeps default LiteLLM) or litellm. Existing codex_app_server values can be loaded, displayed, and exported, but execution returns backend_removed before preparation or acceptance, without switching models, accounts, or providers. In Settings → Agent → Ask-stock method, explicitly choose a supported value and save. Unrelated settings can still be saved; explicitly saving or importing the retired value is rejected without partial writes. Status and draft previews inspect configuration only, without launching Codex or schema/version probes or calling models. Historical conversations, stock identity, Skills, single/multi Agent, and provider trace keep their existing contracts. Standalone GENERATION_BACKEND=codex_cli reports and other generation-only paths are unaffected and still require their original CLI dependencies.
Local CLI Privacy And Boundaries
Section titled “Local CLI Privacy And Boundaries”- A local CLI backend is not an offline model. The service behind Codex / Claude Code / OpenCode may process stock symbols, news, position context, analysis prompts, and report drafts.
- Docker, cloud servers, and CI do not automatically have your local CLI login state.
- GitHub Actions only passes configuration values through; it does not install or log in local CLIs. If you opt into a local CLI backend in Actions, a runner without the executable or login state should return a structured failure.
- DSA does not read Codex/Claude/OpenCode credential files, but the subprocess may use the CLI’s own login state.
- On macOS, desktop apps launched from Finder/Dock do not inherit the shell PATH. The packaged desktop app adds common Homebrew directories such as
/opt/homebrew/binand/usr/local/binwhen starting the backend. If setup checks still cannot find the CLI executable, fully quit and reopen DSA; opening an interactive CLI window does not change the already-running backend PATH. - DSA only inherits a minimal child environment and denies wildcard inheritance of
CLAUDE_*,ANTHROPIC_*,OPENCODE_*,OPENAI_*,GOOGLE_*,GEMINI_*,AWS_*,AZURE_*,VERTEX_*,*_API_KEY,*_AUTH_TOKEN,*_ACCESS_TOKEN,*_SECRET, and*_PASSWORD, reducing the risk of leaking DSA API keys, provider tokens, or webhook tokens.CODEX_HOMEis the exact-name exception retained for existing Codex CLI login-directory compatibility;CODEX_CLI_*wildcard inheritance is not restored. opencode_cliwrites a minimal projectopencode.jsonin the temporary cwd to disable sharing, autoupdate, snapshots, and common tool permissions, but OpenCode’s resolved config may still include local global settings. Runtime safety also relies on--pure, the env denylist, prompt-file permissions, and the event extractor failing closed.- The Web settings page only exposes safe presets; it does not accept arbitrary command, argv, or shell strings.
codex_cli/claude_code_cli/opencode_cliremain experimental/limited. If your CLI version does not support the non-interactive output contract verified by this repository, DSA returns structuredcapability_unsupported,cli_contract_unsupported,invalid_json,schema_validation_failed, or the corresponding backend error, and falls back tolitellmwhen backend fallback is configured. If that version-drift risk is unacceptable, keepGENERATION_BACKEND=litellm.opencode_clidoes not support OpenCode serve / web / ACP / MCP / attach /--dangerously-skip-permissions, and DSA never treats OpenCode final text as Agent tool success.
Method 1: Simple Model Config (For Beginners)
Section titled “Method 1: Simple Model Config (For Beginners)”Goal: Just paste your API Key and the model name to start using it immediately. No need to mess with complex concepts.
If you only plan to use one single model, this is the fastest way. Open the .env file in the project’s root directory (if it doesn’t exist, copy .env.example and rename it to .env).
Modelflare uses standard Channels configuration; see the Modelflare example below. This section retains single-model legacy configuration, and existing setups do not require migration.
Example 1: Using a Third-party OpenAI-Compatible Platform (Highly Recommended)
Section titled “Example 1: Using a Third-party OpenAI-Compatible Platform (Highly Recommended)”Most third-party relay platforms and local API providers support the OpenAI interface format. As long as the platform provides an API Key and a Base URL, you can configure it easily using the following pattern:
# Fill in the API Key provided by your platformOPENAI_API_KEY=sk-xxxxxxxxxxxxxxxx# Fill in the platform's API Base URL (Very Important: Usually must end with /v1)OPENAI_BASE_URL=https://api.siliconflow.cn/v1# Fill in the specific model name (Very Important: You must add the "openai/" prefix so the system recognizes it)LITELLM_MODEL=openai/deepseek-ai/DeepSeek-V3Example 2: Using the Official DeepSeek API
Section titled “Example 2: Using the Official DeepSeek API”# Fill in the API Key requested from the official DeepSeek platformDEEPSEEK_API_KEY=sk-xxxxxxxxxxxxxxxxWith only this line, the system defaults to deepseek/deepseek-v4-flash.
DeepSeek announced the shutdown of deepseek-chat / deepseek-reasoner on 2026/07/24; please migrate old configs. New configs should migrate through the Web quick channel or explicitly set LITELLM_MODEL=deepseek/deepseek-v4-flash for deepseek-v4-flash / deepseek-v4-pro.
Example 3: Using the Free Gemini API
Section titled “Example 3: Using the Free Gemini API”# Fill in your Google Gemini KeyGEMINI_API_KEY=AIzac...Example 4: Using Ollama Local Models
Section titled “Example 4: Using Ollama Local Models”# Ollama requires no API Key; works after running ollama serve locallyOLLAMA_API_BASE=http://localhost:11434LITELLM_MODEL=ollama/qwen3:8bImportant: Ollama must be configured with
OLLAMA_API_BASE. Do not useOPENAI_BASE_URL, or the system will concatenate URLs incorrectly (e.g. 404,api/generate/api/show). For remote Ollama, setOLLAMA_API_BASEto the actual address (e.g.http://192.168.1.100:11434). Current dependency constraint islitellm>=1.80.10,!=1.82.7,!=1.82.8,<1.99.0(matches requirements.txt).
Anspire Open legacy compatibility example
Section titled “Anspire Open legacy compatibility example”Existing Anspire setups that share a key between search and LLMs remain supported. These are configuration examples whose availability depends on your account and the Anspire console; confirm them with the Web “Test connection” action.
# Anspire Open API keys (multiple keys supported, separated by commas)# Get your key at: https://open.anspire.cn/dsa?share_code=QFBC0FYC# When no higher-priority OpenAI-compatible source is set, this key is reused for Anspire search + LLM path (example fallback behavior only).# Example model: Doubao-Seed-2.0-lite; example gateway: https://open-gateway.anspire.cn/v6ANSPIRE_API_KEYS=sk-xxxxxxxxxxxxxxxx# Optional: switch example model or gateway according to your Anspire account and official docs.# ANSPIRE_LLM_MODEL=Doubao-Seed-2.0-pro# ANSPIRE_LLM_BASE_URL=https://open-gateway.anspire.ai/v6Congratulations! If you’re a beginner, you can stop reading here and run the program! Want to test the connection? Open your terminal in the root directory and run:
python scripts/check_env.py --llm
Method 2: Channels Mode Config (Advanced/Multi-model)
Section titled “Method 2: Channels Mode Config (Advanced/Multi-model)”Goal: I have Keys from multiple different platforms and want to use them together. If my primary model fails or the network drops, I want it to automatically switch to fallback models.
Configure via Web UI directly: After starting the application, you can do this visually under System Settings -> AI Model -> AI Model Access in the Web UI.
New editor behavior: For DeepSeek, DashScope, and other OpenAI-compatible providers that expose
/v1/models, the settings page can now fetch models directly from{base_url}/modelsand let you select multiple entries visually. The underlying storage format is still the existing comma-separatedLLM_{CHANNEL}_MODELS=model1,model2value. If a provider does not support/models, authentication fails, or the endpoint is temporarily unavailable, you can still type the model list manually and save normally.
First-run Setup Status
Section titled “First-run Setup Status”The backend exposes a read-only status endpoint at GET /api/v1/system/config/setup/status. It reports whether the minimum first-run pieces are present: primary LLM, Agent model inheritance/configuration, stock list, optional notification channel, and local storage. The endpoint only reads the saved .env plus the current process environment; it does not reload runtime config, write .env, test a real model, or create a database file. Frontend onboarding and later smoke-run flows can build on this endpoint incrementally.
Web channel editor: compatibility, migration, and rollback rules
Section titled “Web channel editor: compatibility, migration, and rollback rules”- The preset provider / API surface / Base URL / sample models are form defaults only. What gets persisted is exactly what you submit in
LLM_{CHANNEL}_PROTOCOL,LLM_{CHANNEL}_API_SURFACE,LLM_{CHANNEL}_BASE_URL,LLM_{CHANNEL}_MODELS, andLLM_{CHANNEL}_API_KEY(S); the editor does not silently rewrite them to a different provider, surface, or URL. LLM_{CHANNEL}_API_SURFACEacceptschat_completions(default) orresponses; Responses currently requires the OpenAI-compatible protocol, and every model’s actual LiteLLM provider must beopenai. Direct prefixes come from the installed LiteLLM provider registry and are returned to the Web editor asllm_model_providersbyGET /api/v1/system/config, so the frontend and backend do not maintain separate provider tables. This preventsanthropic/claude-*,xai/grok-*, and providers added by future LiteLLM versions from being miswrapped as OpenAI routes because of a stale client allow-list. Conflicts are rejected consistently by save validation, runtime loading, status diagnostics, and screening instead of producinganthropic/responses/.... Gateway-owned IDs such asdeepseek-ai/DeepSeek-V3orQwen/...that are absent from the registry are normalized underopenai/<gateway model ID>. All models in one channel must use the same surface, and one normalized route alias cannot mix Chat and Responses across channels because Router load balancing could select the wrong endpoint; use distinct aliases when both surfaces are required. “Discover models” still calls{base_url}/models; “Test connection” sends one minimal request through the selected surface and reportsresolved_modelplusresolved_api_surface. It never retries another endpoint after failure. If the response includesdetails.reason=model_access_denied(for example, the observed Issue #1208 SiliconFlow / OpenAI Compatible sample returnedModel disabledthrough LiteLLM), treat it as a best-effort availability diagnostic: confirm model entitlement for the current key, then adjust the model order or remove unavailable models. Optional capability checks send additional real requests and remain best-effort. Their structured diagnostic fields are never persisted into.envand do not block saving.- If the response includes
details.reason=provider_blocked, the provider or relay gateway explicitly blocked this request. This is distinct from local network / TLS failures andmodel_access_denied; first check account risk controls, region or request-source restrictions, model entitlement, relay gateway policy, and content-safety policy. - Runtime capability checks send real LLM requests and may incur token / image-input cost, RPM/TPM rate limiting, insufficient balance errors, or timeouts. A failed check may come from account permissions, model entitlement, endpoint region, balance, provider compatibility layers, or LiteLLM translation behavior; it does not prove that the provider globally lacks that capability. P3 does not include online smoke coverage for every real provider. Its compatibility basis is the repository dependency constraint
litellm>=1.80.10,!=1.82.7,!=1.82.8,<1.99.0, LiteLLMcompletion()/ OpenAI I/O format / streaming / exception mapping, and the OpenAI Chat Completions shapes for JSON mode, tool calling, streaming, and vision input. - External references: LiteLLM Python SDK / OpenAI I/O format / streaming / exception mapping: https://docs.litellm.ai/; LiteLLM OpenAI-compatible routing: https://docs.litellm.ai/docs/providers/openai_compatible; OpenAI Chat Completions: https://platform.openai.com/docs/api-reference/chat/create; JSON mode: https://platform.openai.com/docs/guides/structured-outputs?api-mode=chat; tool calling: https://platform.openai.com/docs/guides/function-calling?api-mode=chat; streaming: https://platform.openai.com/docs/guides/streaming-responses?api-mode=chat; vision input: https://platform.openai.com/docs/guides/images-vision?api-mode=chat.
- Saving channels only updates the keys submitted in that save operation; there is no whole-config silent migration when you switch channel settings. The one deliberate cleanup is runtime model references: if
LITELLM_MODEL,AGENT_LITELLM_MODEL,VISION_MODEL, orLITELLM_FALLBACK_MODELSpoint to models that no longer exist in the currently enabled channels, the editor clears/removes those stale references before saving so runtime calls do not keep targeting invalid models. Even when enabled channels expose no selectable models, stale managed-provider values without a matching legacy key are cleaned.cohere/*,google/*, andxai/*are kept as explicit direct-env compatibility examples for legacy retention behavior only, and are not a runtime availability guarantee. - Backend consistency basis: runtime validation in
SystemConfigService._validate_llm_runtime_selection(src/services/system_config_service.py) relies on_uses_direct_env_provider(src/config.py). Onlygemini,vertex_ai,anthropic,openai, anddeepseekare treated as managed key-backed providers;cohere,google, andxaiare not in that allowlist, so they remain valid direct provider runtime entries. - Rollback stays minimal: restore the previous channel model list and re-select the runtime models, or restore the previous
LLM_*,LITELLM_MODEL,AGENT_LITELLM_MODEL,VISION_MODEL,LLM_TEMPERATURE, andLLM_USAGE_HMAC_*values from your desktop export / manual.envbackup. No extra migration script is required. - The current dependency constraint for this flow in the repository is
litellm>=1.80.10,!=1.82.7,!=1.82.8,<1.99.0(seerequirements.txt). Regression coverage for it lives intests/test_system_config_service.py,tests/test_system_config_api.py, andapps/dsa-web/src/components/settings/__tests__/LLMChannelEditor.test.tsx.
External provider model examples notice:
cohere/*,google/*, andxai/*provider-prefixed values are included here only to describe current runtime retention behavior and are not a global availability guarantee. Specific model names in docs or tests are configuration-retention examples, not production recommendations. Check the provider’s official model/API docs and validate against the repository dependency constraintlitellm>=1.80.10,!=1.82.7,!=1.82.8,<1.99.0before production use.
Rollback & compatibility evidence
Section titled “Rollback & compatibility evidence”- Scope and cleanup behavior under
litellm>=1.80.10,!=1.82.7,!=1.82.8,<1.99.0: only runtime references (LITELLM_MODEL,AGENT_LITELLM_MODEL,VISION_MODEL,LITELLM_FALLBACK_MODELS) are sanitized during save; non-channel direct providers such ascohere/*,google/*, andxai/*are preserved. - Rollback path: export desktop config, then restore the backup through
POST /api/v1/system/config/import; or manually restore historical.enventries (LITELLM_*,AGENT_LITELLM_MODEL,VISION_MODEL,LLM_TEMPERATURE,LLM_USAGE_HMAC_*) and restart. - Rollback evidence:
tests/test_system_config_service.py::test_import_desktop_env_restores_runtime_models_after_cleanupcovers restore from exported desktop backup after runtime cleanup. - Direct-provider evidence:
tests/test_system_config_service.py::SystemConfigServiceTestCase::test_validate_accepts_minimax_model_as_direct_env_provider,test_validate_accepts_cohere_model_as_direct_env_provider,test_validate_accepts_google_model_as_direct_env_provider, andtest_validate_accepts_xai_model_as_direct_env_providercover the preserved direct-provider behavior. - Frontend regression commands:
cd apps/dsa-web && npm run lint && npm run build && npm run test -- src/components/settings/__tests__/LLMChannelEditor.test.tsx. - Recommended rollback sequence (including UI reload): export desktop backup, restore via
POST /api/v1/system/config/import, then callGET /api/v1/system/configto refresh the settings page and verifyLITELLM_MODEL/AGENT_LITELLM_MODEL/VISION_MODEL/LLM_TEMPERATUREbefore continuing.
Official references for provider presets / Base URLs / model naming
Section titled “Official references for provider presets / Base URLs / model naming”- Modelflare: Quickstart, Endpoints, Models and groups
- OpenAI-compatible routing in LiteLLM: https://docs.litellm.ai/docs/providers/openai_compatible
- OpenAI official API docs: https://platform.openai.com/docs/api-reference/chat
- DeepSeek official API docs: https://api-docs.deepseek.com/
- Anspire Open: https://open.anspire.cn/dsa?share_code=QFBC0FYC
- DashScope OpenAI-compatible mode: https://help.aliyun.com/zh/model-studio/compatibility-of-openai-with-dashscope
- Moonshot / Kimi official compatibility docs: https://platform.moonshot.ai/docs/guide/compatibility
- Anthropic official Messages API: https://docs.anthropic.com/en/api/messages
- Gemini official OpenAI compatibility docs: https://ai.google.dev/gemini-api/docs/openai
- Cohere official: https://docs.cohere.com/
- Cohere API reference: https://docs.cohere.com/reference/
- Cohere LiteLLM provider page: https://docs.litellm.ai/docs/providers/cohere
- Google Gemini API and model list: https://ai.google.dev/gemini-api/docs/openai, https://ai.google.dev/gemini-api/docs/models
- Google LiteLLM provider page: https://docs.litellm.ai/docs/providers/gemini
- xAI official: https://docs.x.ai/docs
- xAI LiteLLM provider page: https://docs.litellm.ai/docs/providers/xai
- Ollama API docs: https://github.com/ollama/ollama/blob/main/docs/api.md
If you prefer modifying files, configuring this in the .env file is also very smooth. It allows you to manage multiple platforms simultaneously. The rules are:
- Declare your channels first:
LLM_CHANNELS=channel_name_1,channel_name_2 - Provide configurations for each channel (Note the uppercase):
LLM_{CHANNEL_NAME}_XXX
Example: Modelflare
Section titled “Example: Modelflare”Register with Modelflare, create an API key in the console, and configure:
MODELFLARE_KEY=sk-xxxWith MODELFLARE_KEY alone, the backend enables Modelflare and uses https://modelflare.dev/v1 and openai/gpt-6.1-sol. No channel, endpoint or model variables are required. Explicit YAML or LLM_CHANNELS takes precedence; explicit Modelflare channel keys override this shorthand. Clear the key or disable the channel to stop using it. Inference does not rewrite saved configuration.
When modelflare is the only declared channel and its model list is blank, the backend defaults to openai/gpt-6.1-sol if no primary model is configured; otherwise it reuses LITELLM_MODEL and OpenAI-prefixed fallback routes. Use openai/<model> for the primary model. An explicit channel list takes precedence; multi-channel setups must declare each channel’s models. Inference does not rewrite saved configuration or change model selection.
For the channel named modelflare, an omitted or blank Base URL defaults to https://modelflare.dev/v1; an explicit LLM_MODELFLARE_BASE_URL takes precedence. Protocol defaults to openai for this endpoint and the API surface to chat_completions. When LITELLM_MODEL is unset, the first channel model is selected. The default model still requires account access; no API key is supplied automatically.
gpt-6.1-sol is this project’s Modelflare default. Select models available to your account and confirm them with the Web editor’s “Discover models” and “Test connection” actions; do not append /chat/completions to the Base URL. Modelflare is the initially selected template for new channels. Reordering templates does not change saved channels or primary models. Anspire Search continues to use ANSPIRE_API_KEYS independently.
Both the client’s quick-add registration button and the exclusive registration link in channel details use the app UTM; README links use the github UTM. If a new channel has no key yet, or the primary/fallback model is not declared by an enabled channel, status preview shows the affected configuration fields. Supply the key, select available models or clear invalid fallback selections, then retry. Preview does not rewrite saved settings.
Example: x6.ai
Section titled “Example: x6.ai”Select x6.ai in the Web settings, enter your key, discover models and test the connection. For environment variables and GitHub Actions, use the x6.ai channel example; the key alone does not enable an explicit channel.
Compatibility example: Anspire Responses API (observed GPT-5.6 model names)
Section titled “Compatibility example: Anspire Responses API (observed GPT-5.6 model names)”LLM_CHANNELS=anspireLLM_ANSPIRE_PROTOCOL=openaiLLM_ANSPIRE_API_SURFACE=responsesLLM_ANSPIRE_BASE_URL=https://open-gateway.anspire.cn/v6LLM_ANSPIRE_API_KEY=sk-xxxLLM_ANSPIRE_MODELS=gpt-5.6-sol,gpt-5.6-terra,gpt-5.6-lunaLITELLM_MODEL=openai/gpt-5.6-solLITELLM_FALLBACK_MODELS=openai/gpt-5.6-terra,openai/gpt-5.6-lunaAnspire’s official integration page documents https://open-gateway.anspire.cn/v6/responses: https://open.anspire.cn/model?link=sample&tab=models. Responses routing is not hard-coded to model names; the GPT-5.6 names above are current gateway observations rather than a durable model-catalog promise. Treat the live /models response, provider guidance, and connection test as authoritative for the model, Surface, availability, and account access.
Example: Configuring DeepSeek and a Third-party Relay with Fallbacks
Section titled “Example: Configuring DeepSeek and a Third-party Relay with Fallbacks”# 1. Enable channel mode, declare two channels here: deepseek and aihubmixLLM_CHANNELS=deepseek,aihubmix
# 2. Channel 1: Configure Official DeepSeekLLM_DEEPSEEK_BASE_URL=https://api.deepseek.comLLM_DEEPSEEK_API_KEY=sk-1111111111111LLM_DEEPSEEK_MODELS=deepseek-v4-flash,deepseek-v4-pro
# 3. Channel 2: Configure a common relay/proxy APILLM_AIHUBMIX_BASE_URL=https://api.aihubmix.com/v1LLM_AIHUBMIX_API_KEY=sk-2222222222222LLM_AIHUBMIX_MODELS=gpt-6.1-sol,claude-sonnet-4-6
# 4. [Key Step] Specify the primary model and fallback list# Set your primary model:LITELLM_MODEL=deepseek/deepseek-v4-flash# Optional: set an Agent-only primary model (empty = inherit the primary model)AGENT_LITELLM_MODEL=deepseek/deepseek-v4-pro# If the primary model crashes, try these fallbacks sequentially:LITELLM_FALLBACK_MODELS=openai/gpt-6.1-terra,anthropic/claude-sonnet-4-6Example: Ollama Channel Mode (Local Models, No API Key)
Section titled “Example: Ollama Channel Mode (Local Models, No API Key)”# 1. Enable channel mode, declare ollama channelLLM_CHANNELS=ollama
# 2. Configure Ollama address (default local port 11434)LLM_OLLAMA_BASE_URL=http://localhost:11434LLM_OLLAMA_MODELS=qwen3:8b,llama3.2
# 3. Specify primary modelLITELLM_MODEL=ollama/qwen3:8bExample: Hermes Local HTTP Generation (Phase 3)
Section titled “Example: Hermes Local HTTP Generation (Phase 3)”LLM_CHANNELS=hermesLLM_HERMES_PROTOCOL=openaiLLM_HERMES_BASE_URL=http://127.0.0.1:8642/v1LLM_HERMES_API_KEY=sk-local-hermesLLM_HERMES_MODELS=hermes-agentLITELLM_MODEL=openai/hermes-agenthermes is a reserved channel name for local loopback /v1 OpenAI-compatible generation. Phase 3 only verifies regular analysis and JSON output. It does not support Stream/SSE, tools, Vision, Agent tools, remote Hermes, or process lifecycle management. Use exactly one LLM_HERMES_API_KEY; do not configure LLM_HERMES_API_KEYS or LLM_HERMES_EXTRA_HEADERS. If enabled Hermes config is invalid, DSA blocks legacy provider silent fallback so requests do not unexpectedly switch to an external model. When the Web settings page saves the reserved Hermes channel, it explicitly clears stale LLM_HERMES_API_KEYS / LLM_HERMES_EXTRA_HEADERS values and returns a warning. To recover previous values, restore them from a .env backup, Git history, or a desktop export backup, but Phase 3 will still reject non-empty multi-key or extra-header Hermes settings.
MiniMax Model Naming in Channel Mode
Section titled “MiniMax Model Naming in Channel Mode”- For the official OpenAI-compatible MiniMax channel, use
MiniMax-M3.1-Flash,MiniMax-M3. Explicit saved provider-prefixed IDs such asminimax/MiniMax-M3.1-Flashremain supported. - The Web settings page now keeps that value unchanged in Primary, Agent Primary, Fallback, and Vision selectors instead of rewriting it to
openai/minimax/<model-name>.
Default-Model Ask-Stock / LiteLLM Compatibility Notes
Section titled “Default-Model Ask-Stock / LiteLLM Compatibility Notes”- With
AGENT_BACKEND=auto|litellm, ask-stock follows the same three-tier runtime priority as the regular analyzer:LITELLM_CONFIG(LiteLLM YAML) >LLM_CHANNELS> legacy provider keys. Once an upper tier is valid and active, lower tiers are ignored for that request. - In YAML mode, the Agent reuses LiteLLM
model_list/model_namerouting semantics directly. In channel mode, it first readsAGENT_LITELLM_MODEL; when that is empty it inheritsLITELLM_MODEL, then continues throughLITELLM_FALLBACK_MODELS. - If you do not use YAML or Channels, leave
AGENT_LITELLM_MODELempty, and still rely on legacy provider env vars, the ask-stock Agent continues to inherit them:GEMINI_API_KEY + GEMINI_MODEL->gemini/<model>,OPENAI_API_KEY + OPENAI_MODEL->openai/<model>, andANTHROPIC_API_KEY + ANTHROPIC_MODEL->anthropic/<model>. - This fix only improves two things: preserving the backend’s real failure reason and returning a more specific diagnostic when no usable Agent LLM is configured. It does not silently delete, clear, migrate, or rewrite your existing
GEMINI_*,OPENAI_*,ANTHROPIC_*, orLITELLM_*settings. - If the current environment has no valid Agent model path at all, the ask-stock page still returns a failure and now surfaces the backend’s real configuration diagnosis. As soon as you restore any valid model source, the flow recovers without running any migration step.
- The recommended forward path is still to configure
LITELLM_MODEL/AGENT_LITELLM_MODELexplicitly or move toLLM_CHANNELS; legacy provider keys remain a compatibility fallback for older.envfiles, local macOS development, and existing deployments.
Ask-Stock Visible Chat Context Compression
Section titled “Ask-Stock Visible Chat Context Compression”By default, ask-stock injects only the 20 most recent visible messages. Enable LLM context compression to reduce long-conversation token usage:
AGENT_CONTEXT_COMPRESSION_ENABLED=trueAGENT_CONTEXT_COMPRESSION_PROFILE=balanced# Blank values follow the selected profile presetAGENT_CONTEXT_COMPRESSION_TRIGGER_TOKENS=AGENT_CONTEXT_PROTECTED_TURNS=Compression processes only visible user / assistant text under the same session_id. It does not process provider traces, thinking blocks, tool calls, or tool results, and it does not change same-turn tool passthrough. The presets are cost (6000 tokens / 2 protected turns), balanced (12000 / 4), and long_context_raw_first (24000 / 6). Blank trigger/protected values follow the selected profile; explicit values override it.
For the single-agent ask-stock path, the backend also keeps a provider-aware trace track for DeepSeek V4 thinking + tool-call roundtrip. A trace is persisted only when the same run has both tool_calls and reasoning_content; the last 3 minimal protocol slices per session_id + provider + model are spliced back into the next request before the anchored visible assistant reply. Provider trace is either preserved exactly or dropped as a whole; it is never summarized, never returned by Web session-history APIs, and adds no .env setting. Model/provider mismatch, summarized anchors, or insufficient budget drop the whole trace. Claude extended thinking is limited in this PR to adapter/storage-level opaque thinking / redacted_thinking / signature block plumbing with offline fixtures; production end-to-end Claude and multi-agent trace injection remain follow-ups. Protocol references: DeepSeek thinking mode (https://api-docs.deepseek.com/guides/thinking_mode) and Anthropic Claude extended thinking (https://platform.claude.com/docs/en/docs/build-with-claude/extended-thinking). The LiteLLM compatibility window remains litellm>=1.80.10,!=1.82.7,!=1.82.8,<1.99.0 from requirements.txt.
Strict Temperature Model Compatibility Notes
Section titled “Strict Temperature Model Compatibility Notes”- Moonshot officially documents Kimi as an OpenAI-compatible API, with
https://api.moonshot.ai/v1as the base URL: https://platform.kimi.ai/docs/guide/kimi-k2-6-quickstart - LiteLLM officially requires the
openai/prefix for OpenAI-compatible model routing: https://docs.litellm.ai/docs/providers/openai_compatible - Moonshot’s compatibility docs distinguish two fixed values: thinking mode must use
1.0, while non-thinking mode must use0.6; other values are rejected by the API: https://platform.moonshot.ai/docs/guide/compatibility#parameters-differences-in-request-body - The OpenAI Chat Completions API treats
temperatureas optional. For GPT-5 / GPT-6 / o-series style models that only accept the provider default temperature, this project omitstemperatureat request time instead of rewriting your savedLLM_TEMPERATURE: https://platform.openai.com/docs/api-reference/chat/create - The current runtime dependency constraint in this repository is
litellm>=1.80.10,!=1.82.7,!=1.82.8,<1.99.0(seerequirements.txt); this compatibility fix is regression-covered under that constraint across the main analyzer, market review, direct Agent LiteLLM calls, and the system-settings channel connectivity test path. - This repository therefore normalizes
kimi-k2.6andkimi-k2.6-*right before dispatch based on the actual request mode: default / thinking requests usetemperature=1.0; if your LiteLLM YAML route alias explicitly setslitellm_params.extra_body.thinking.type: disabled(or an equivalent non-thinking override), it automatically switches totemperature=0.6. Your savedLLM_TEMPERATUREvalue in.envor the Web settings is not rewritten. - If a compatible platform returns an explicit parameter error for a not-yet-profiled model, such as unsupported
temperature, default-only1.0, or unsupportedtop_p, the runtime repairs the current request and retries once. The strategy is cached only in the current process after the retry succeeds; it is never written back to.env, and a service restart re-evaluates the configured rules normally. - For streaming responses that already produced partial content, the runtime does not switch parameters mid-output. It keeps the existing same-model non-stream retry / fallback-model path to avoid stitching inconsistent answers together.
SystemConfigServiceonly updates keys that you actually submit when saving from the Web settings page or importing a desktop.env; switching to a strict-temperature model does not silently clear, migrate, or rewrite an existingLLM_TEMPERATURE. Temporary request-time parameter strategies are not persisted back into the config file.- Non-strict primary models, non-strict fallbacks, and any request after switching back to a regular model still use your configured temperature. Existing configs do not need migration; changing the model restores the original behavior automatically.
- Repository-side compatibility coverage lives in
tests/test_llm_channel_config.py,tests/test_market_analyzer_generate_text.py,tests/test_agent_pipeline.py, andtests/test_system_config_service.py. - Minimal rollback: revert only the LLM generation-parameter adaptation change set; no separate
LLM_TEMPERATUREmigration is required.
Critical Warning: If you enable
LLM_CHANNELS, any standardDEEPSEEK_API_KEYorOPENAI_API_KEYdeclared independently will be completely ignored. Use only one mode to prevent configuration conflicts. Docker note: IfLITELLM_MODEL,LLM_CHANNELS,LLM_DEEPSEEK_MODELS, or related variables are explicitly passed throughdocker compose environment:ordocker run -e, they will override the.envwritten by the Web settings page after a container restart. Update the deployment environment at the same time.
Compatibility evidence and rollback audit notes (for this recovery change)
Section titled “Compatibility evidence and rollback audit notes (for this recovery change)”- Compatibility is validated in two layers: first-party provider/API contract references (LiteLLM OpenAI-compatible routing, OpenAI Chat Completions, Moonshot/Kimi docs and model notes), and second the current runtime implementation in this repository under
litellm>=1.80.10,!=1.82.7,!=1.82.8,<1.99.0. - This recovery path is runtime-only and intentionally local: exception classification + one in-request repair retry + in-process cache. It does not rewrite
.env, migrate saved config keys, or alter legacy values; it only omits/adjusts request parameters (temperature,top_p,presence_penalty,frequency_penalty,seed) for the current call. Rolling back requires no migration; restore previous settings and model/provider selection. - Regression evidence for this path is in
tests/test_llm_param_recovery.py,tests/test_system_config_service.py,tests/test_llm_channel_config.py,tests/test_system_config_api.py,tests/test_market_analyzer_generate_text.py,tests/test_agent_pipeline.py; desktop backup import restore is directly covered bytest_import_desktop_env_restores_runtime_models_after_cleanup.
Method 3: Advanced YAML Config (Expert Setup)
Section titled “Method 3: Advanced YAML Config (Expert Setup)”Goal: I want maximum control and origin-level routing rules for enterprise-grade high availability.
This layer maps directly to the underlying LiteLLM routing capabilities, including high concurrency, automatic retries, and TPM/RPM-based load balancing.
- Keep only one declaration line in your
.env:LITELLM_CONFIG=./litellm_config.yaml - Create a
litellm_config.yamlin the project root directory (you can refer todocs/examples/litellm_config.example.yaml).
Example litellm_config.yaml:
model_list: - model_name: my-smart-model litellm_params: model: deepseek/deepseek-v4-flash api_base: https://api.deepseek.com api_key: "os.environ/MY_CUSTOM_SECRET_KEY" # Fetch from environment vars for security
# Ollama local model (no api_key needed) - model_name: ollama/qwen3:8b litellm_params: model: ollama/qwen3:8b api_base: http://localhost:11434Priority Rule: YAML is king! If YAML is configured, both Channels Mode and Simple Mode are entirely ignored. Hierarchy:
YAML > Channels > Simple.
LLM usage HMAC telemetry
Section titled “LLM usage HMAC telemetry”P0a usage telemetry creates HMAC-SHA256 fingerprints for the actual messages sent to the model. This only writes local llm_usage telemetry. It does not change prompts, provider parameters, cache hints, model output, or fallback order.
Usage is read in three tiers:
- Prefer the provider / LiteLLM public
usageresponse field. - Then read the LiteLLM public
usage_metadataresponse field. - Only then read
_hidden_params["usage"], which is a LiteLLM private/internal best-effort fallback rather than a stable public contract. If it is absent, usage/cache telemetry may be incomplete; the model request itself has not failed for that reason.
Cache-token normalization is allowlisted best-effort normalization only. The external field evidence and runtime boundaries are separated below so provider contracts, current LiteLLM normalization behavior, and repository-specific compatibility allowlists are not treated as the same thing:
| Provider / source | Fields read | Evidence and boundary | Coverage |
|---|---|---|---|
| OpenAI | usage.prompt_tokens_details.cached_tokens |
The official Prompt Caching docs state that requests below 1024 tokens still expose cached_tokens=0: https://developers.openai.com/api/docs/guides/prompt-caching |
Covered by unit/mock tests; this PR does not include OpenAI live smoke |
| Anthropic | cache_creation_input_tokens / cache_read_input_tokens / input_tokens |
The official Prompt Caching docs define total_input_tokens = cache_read_input_tokens + cache_creation_input_tokens + input_tokens: https://platform.claude.com/docs/en/build-with-claude/prompt-caching |
Covered by unit/mock tests; this PR does not include Anthropic live smoke |
| Gemini / Vertex AI | Official source field: UsageMetadata.cachedContentTokenCount; runtime consumes LiteLLM-exposed snake_case / normalized fields such as cached_content_token_count, cache_read_input_tokens, or prompt_tokens_details.cached_tokens |
Gemini UsageMetadata official field: https://ai.google.dev/api/generate-content#UsageMetadata. This repository does not add native camelCase runtime fallback; runtime compatibility is bounded to litellm>=1.80.10,!=1.82.7,!=1.82.8,<1.99.0 |
Covered by unit/mock tests; this PR does not include Gemini / Vertex live smoke |
| DeepSeek | prompt_cache_hit_tokens / prompt_cache_miss_tokens |
DeepSeek Chat Completion docs state that prompt_tokens = prompt_cache_hit_tokens + prompt_cache_miss_tokens: https://api-docs.deepseek.com/api/create-chat-completion |
Covered by unit/mock tests; this PR includes one redacted DeepSeek smoke only and does not store the full response |
| GLM / OpenAI-compatible / StepFun and similar compatible platforms | Values from the modeled token/cache count allowlist that can be normalized to common fields | No stable official cache telemetry contract is claimed here; this is best-effort normalization under the current LiteLLM / OpenAI-compatible shape. Unmodeled metadata is not persisted | Covered by unit/fixture/mock tests; this PR does not include live smoke for these providers |
| LiteLLM public response shape | usage / usage_metadata |
Consumed according to the response / Usage object shape in the current dependency window litellm>=1.80.10,!=1.82.7,!=1.82.8,<1.99.0; this is not a LiteLLM 2.x compatibility guarantee |
Covered by Analyzer / Agent / usage tests |
| LiteLLM private fallback | _hidden_params["usage"] |
Private/internal best-effort fallback, not a stable LiteLLM public contract. It only fills narrow streaming telemetry gaps such as public zero-only/no-signal usage and does not change provider request parameters | Covered by unit/mock tests; absence only affects telemetry completeness, not model request success |
LLM_USAGE_HMAC_SECRET=LLM_USAGE_HMAC_KEY_VERSION=local-v1- When
LLM_USAGE_HMAC_SECRETis empty, the backend creates.llm_usage_hmac_secretin the data directory for local deployment-scoped comparisons. - Set the same high-entropy random secret only when multiple deployments intentionally need comparable HMACs; generate one with
openssl rand -hex 32. .llm_usage_hmac_secretis a local secret artifact and is ignored by filename in.gitignore.- When rotating the secret, update
LLM_USAGE_HMAC_KEY_VERSIONso old and new fingerprints are not compared as if they used the same key. - Do not reuse the login session secret and do not commit or expose the real secret in version control, issues, logs, or screenshots.
Provider prompt cache configuration (P1 / P1.5)
Section titled “Provider prompt cache configuration (P1 / P1.5)”Prompt-cache settings only control whether this project records cache usage / diagnostics and whether the main analysis path actively sends verified provider-specific hints. They do not control implicit or provider-managed cache behavior in OpenAI, Gemini, DeepSeek, or other providers.
LLM_PROMPT_CACHE_TELEMETRY_ENABLED=trueLLM_PROMPT_CACHE_HINTS_ENABLED=falseLLM_PROMPT_CACHE_DIAGNOSTICS_LEVEL=off- When
LLM_PROMPT_CACHE_TELEMETRY_ENABLED=false, provider raw usage JSON, normalized cache fields, and cache-decision diagnostics are not persisted. Basic token usage remains compatible. LLM_PROMPT_CACHE_HINTS_ENABLED=trueonly allows the main analysis / analyzer LiteLLM path to sendprompt_cache_key,cache_control,user_id, and similar hints for provider / route entries that are verified or smoke-tested in the registry. The ask-stock Agent path currently records capability / usage diagnostics only and does not actively send provider-specific hints. Unknown OpenAI-compatible gateways stay telemetry-only.LLM_PROMPT_CACHE_DIAGNOSTICS_LEVEL=basicprovides non-sensitive enum decisions such as provider, API surface, verification status, hint applied, and disabled reason only through debug logs and test-observable objects.debugadds HMAC-derived route/cache diagnostics and matched caps id on the same surfaces, but still must not include raw prompts, request bodies, message content, raw stock/user values, webhooks, or API keys. These diagnostics are not public Usage API or ordinary settings-page output.- The Provider Cache Capability Registry is a code-level manual registry in
src/llm/provider_cache.py. Entries includedoc_sources,last_verified_at, andverification_status; update them with tests when adding providers or upgrading LiteLLM. - Prompt cache keys, route keys, and DeepSeek session isolation reuse
LLM_USAGE_HMAC_SECRET/.llm_usage_hmac_secretwith domain-separated HMACs. No prompt-cache-specific secret is introduced.
Legacy message stability audit (P0.5a)
Section titled “Legacy message stability audit (P0.5a)”P0.5a adds internal stability-audit fields for the ordinary stock-analysis legacy [system, user] message path. The fields are written only to local llm_usage records. They reuse the message HMAC pipeline above and do not change prompt text, message order, provider request parameters, cache hints, model output, fallback order, the public Usage API, or Web pages.
The added fields are for maintainer diagnostics only:
language,market_group,analysis_mode,legacy_prompt_mode,provider,transport, andmessage_countdescribe low-sensitivity routing context for the stock-analysis call.skill_config_hmacis an HMAC-SHA256 over the resolved skill prompt fragments, default skill policy, and legacy prompt mode. It lets maintainers tell whether the system message changes with skill configuration without storing raw skill text.known_dynamic_marker_positionsis a JSON string. Each entry stores onlymarker_name,message_role, andchar_offset; it does not store stock codes, stock names, dates, news body text, quote values, headers, response text, or prompt snippets.estimated_total_prompt_tokens,approx_common_prefix_chars, andapprox_common_prefix_tokensuse the repository’s stable canonical render: messages are concatenated in order asrole + "\n" + contentwith a fixed separator. This is not claimed to match provider wire bytes.char_offsetis measured inside the matching messagecontent.approx_common_prefix_charsis the character count from canonical-render start to the first known dynamic marker. When no marker is found, common-prefix fields stayNULL.- Token estimates use
ceil(chars / 3). They are diagnostics only, do not replace provider usage, and are not used for cache-threshold decisions; Chinese text can be underestimated.
P0.5a does not introduce PromptBlock IR, block_id, stability_class, static_prefix_hash, or dynamic_context_hash. Agent, research, and market-review paths are not wired into this audit yet.
GitHub Actions Notes
Section titled “GitHub Actions Notes”The bundled 00-daily-analysis.yml explicitly passes the common LLM runtime fields to the job environment:
- Runtime selection:
GENERATION_BACKEND,GENERATION_FALLBACK_BACKEND,GENERATION_BACKEND_TIMEOUT_SECONDS,GENERATION_BACKEND_MAX_OUTPUT_BYTES,GENERATION_BACKEND_MAX_CONCURRENCY,LOCAL_CLI_BACKEND_MAX_CONCURRENCY,AGENT_GENERATION_BACKEND,LLM_CHANNELS,LITELLM_MODEL,LITELLM_FALLBACK_MODELS,AGENT_LITELLM_MODEL,VISION_MODEL,VISION_PROVIDER_PRIORITY,LLM_TEMPERATURE,LLM_USAGE_HMAC_SECRET,LLM_USAGE_HMAC_KEY_VERSION,LLM_PROMPT_CACHE_TELEMETRY_ENABLED,LLM_PROMPT_CACHE_HINTS_ENABLED,LLM_PROMPT_CACHE_DIAGNOSTICS_LEVEL - Multiple keys:
GEMINI_API_KEYS,ANTHROPIC_API_KEYS,OPENAI_API_KEYS,DEEPSEEK_API_KEYS(the current workflow imports these from repository Secrets only, not from same-named Variables) - Common channel names:
modelflare,primary,secondary,aihubmix,anspire,deepseek,dashscope,zhipu,moonshot,minimax,volcengine,siliconflow,openrouter,requesty,gemini,anthropic,openai,ollama,hermes
For example, if you set LLM_CHANNELS=primary,deepseek in GitHub Actions, also configure the corresponding LLM_PRIMARY_* and LLM_DEEPSEEK_* entries. The LLM_<NAME>_API_KEY / LLM_<NAME>_API_KEYS fields are also imported from repository Secrets only right now, so storing them in Variables will not work at runtime. If you use a custom channel name such as my_proxy, GitHub Actions must explicitly add matching LLM_MY_PROXY_* mappings in the workflow env: block. Local .env and Docker runs do not have this limitation.
Advanced Feature: Vision Model Config
Section titled “Advanced Feature: Vision Model Config”Certain specific features in our system (like uploading a stock chart screenshot to extract the stock code) require models capable of computer vision. You need to assign a dedicated vision model in your .env.
# Specify your dedicated vision model nameVISION_MODEL=openai/gpt-6.1-sol# Make sure to provide its corresponding provider API KEY (e.g., OPENAI_API_KEY):# OPENAI_API_KEY=xxxVision Fallback Mechanism: To prevent unexpected failures, the system has a built-in fallback strategy. If the primary vision model fails, it will attempt to use alternative vision-capable provider keys in the following order:
# Default fallback sequence:VISION_PROVIDER_PRIORITY=gemini,anthropic,openaiTroubleshooting
Section titled “Troubleshooting”Afraid you got the config wrong? Type the following commands in your terminal to diagnose:
python scripts/check_env.py --config: Only verifies if the logic in your.envis structurally correct. (Provides instant results, no network calls, strictly checks for syntax omissions).python scripts/check_env.py --llm: Sends a real greeting to the LLM to test the actual endpoint. This thoroughly verifies if your network is working and if your account has sufficient balance.
Common Pitfalls
Section titled “Common Pitfalls”| Weird Error You Got? | Likely Culprit | How to Fix It? |
|---|---|---|
| The UI says the primary model is not configured | The system doesn’t know which provider/model you want to use. | Add a clear instruction in .env: LITELLM_MODEL=provider/your_model_name. Example: openai/gpt-6.1-sol. |
| I added multiple provider Keys, why is only one working? | You mixed the Simple Mode and Channels Mode! | Choose one path. For simple setups, delete anything starting with LLM_CHANNELS. To use multi-model fallbacks, migrate all your Keys into the LLM_CHANNELS setup. |
| Returns 400, 401, or Invalid API Key | The API Key is wrong, copied incompletely, account lacks credits, or you mistyped the model name (extremely common). | 1. Ensure there are no spaces at the start/end of your Key. 2. Ensure your Base URL ends with /v1.3. Check if you forgot the openai/ prefix on the model name! |
Kimi K2.6 returns invalid temperature (it may say only 1.0 or 0.6 is allowed) |
The model requires different fixed temperatures for thinking vs non-thinking mode, while older config or call paths may still pass 0.7. |
After this fix, default / thinking kimi-k2.6 requests automatically use temperature=1.0; if you explicitly disable thinking in a LiteLLM YAML route, the request automatically uses 0.6 instead. Prefer openai/kimi-k2.6 with your Moonshot or relay OpenAI-compatible Base URL and API key. Non-Kimi fallbacks still keep your configured LLM_TEMPERATURE. |
GPT-5 / GPT-6 / o-series returns that temperature is unsupported or only the default is allowed |
These models only accept the provider default sampling parameters, while older call paths may still send 0.7. |
The request layer now omits temperature so the provider default is used. Your .env / Web LLM_TEMPERATURE is not rewritten, and regular models keep using it after you switch back. |
| Spins endlessly, eventually hits Timeout/ConnectionRefused | You are using restricted APIs (like Google/OpenAI) in a blocked region without a proxy, or your cloud server lacks external internet access. | Highly recommend using official regional APIs (like DeepSeek) or OpenAI-compatible relay platforms. Third-party platforms bypass these network constraints. |
Ollama returns 404, Could not get model info, or api/generate/api/show |
Using OPENAI_BASE_URL for Ollama makes the system concatenate URLs incorrectly |
Use OLLAMA_API_BASE=http://localhost:11434 or channel mode (LLM_CHANNELS=ollama + LLM_OLLAMA_BASE_URL) instead |
Veteran’s Tip: If you enable Agent Mode (Deep-thinking & web-search), experience shows you should use a stronger model like deepseek-v4-pro. Trying to save money by using weak mini-models for agents will likely result in infinite loops or missed objectives.