You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
Query Intelligence is the owned backend core of FinSight, the ARIN7012 Group 4.2 evidence-first financial analysis chatbot project. It turns a financial query into two evidence artifacts:
nlu_result: what the user asked, what entities were resolved, what evidence is needed, and which sources should run.
retrieval_result: what evidence was found, how complete it is, how it was ranked, and what structured analysis signals are available.
Downstream systems must consume these artifacts instead of re-inferring intent, targets, or source plans. The local browser chatbot at GET / and POST /chat is one such downstream wrapper; see Local Frontend Chatbot.
Scope and Boundaries
Default shipped runtime coverage is China-market v1:
Unsupported or non-financial questions should be marked out_of_scope.
NLU and Retrieval use explainable methods as their main path: rules, dictionaries, TF-IDF, linear classifiers, CRF, tree models, learning-to-rank, and provider-backed structured retrieval. sentiment/, scripts/llm_response.py, and /chat are downstream exceptions and may use transformer or LLM models over compact evidence.
Architecture
flowchart TD
A["Frontend Query"] --> B["FastAPI /query/intelligence"]
B --> C["NLU Pipeline"]
C --> C1["Normalizer"]
C --> C2["Entity Resolver + Alias + CRF + Typo Linker"]
C --> C3["Product / Intent / Topic / Style / Sentiment Models"]
C --> C4["Out-of-Scope + Clarification Gate"]
C --> C5["Source Planner + Source Plan Reranker"]
C --> D["nlu_result.json"]
D --> E["Retrieval Pipeline"]
E --> E1["Query Builder"]
E --> E2["Document Retriever + Live News + Cninfo"]
E --> E3["Structured Providers: Tushare / AKShare / Postgres / Seed"]
E --> E4["Feature Builder + ML Ranker + Deduper + Selector"]
E --> E5["MarketAnalyzer: Technical Indicators + Valuation + Macro Direction"]
E --> F["retrieval_result.json"]
F --> G["sentiment/"]
F --> H["scripts/llm_response.py"]
F --> I["/chat Browser Chatbot"]
Loading
Key Paths
Path
Description
query_intelligence/api/app.py
FastAPI app.
query_intelligence/service.py
Orchestrates NLU and retrieval.
query_intelligence/contracts.py
Pydantic request/response contracts.
query_intelligence/config.py
Environment-driven settings.
query_intelligence/data_loader.py
Runtime CSV/JSON loaders.
query_intelligence/nlu/pipeline.py
NLU chain.
query_intelligence/retrieval/pipeline.py
Retrieval chain.
query_intelligence/retrieval/market_analyzer.py
Technical indicators and analysis_summary.
query_intelligence/integrations/
Tushare, AKShare, Cninfo, efinance providers.
schemas/
JSON Schemas for external validation.
API
API code is in query_intelligence/api/app.py.
Endpoint
Purpose
Input
Output
GET /health
Health check
none
{"status":"ok"}
GET /
Browser chatbot UI
browser
HTML app
POST /chat
End-to-end NLU + Retrieval + LLM API response polishing
ChatRequest
Chatbot response JSON
POST /nlu/analyze
NLU only
AnalyzeRequest
NLUResult
POST /retrieval/search
Retrieval from an existing NLU result
RetrievalRequest
RetrievalResult
POST /query/intelligence
End-to-end NLU + Retrieval
PipelineRequest
PipelineResponse
POST /query/intelligence/artifacts
End-to-end run and write files
ArtifactRequest
ArtifactResponse
Pipeline Request
{
"query": "What do you think about Ping An Insurance (601318.SH)?",
"user_profile": {
"risk_preference": "balanced",
"preferred_market": "cn",
"holding_symbols": ["601318.SH"]
},
"dialog_context": [
{
"role": "user",
"content": "I hold Ping An Insurance."
}
],
"top_k": 10,
"debug": false
}
Field
Type
Required
Description
query
string
yes
Raw user query, 1 to 2000 characters.
user_profile
object
no
Holdings, risk preference, preferred market, or other caller metadata.
dialog_context
array
no
Prior turns, previous entities, or clarification state.
top_k
integer
no
Retrieval output limit, 1 to 100, default 20.
debug
boolean
no
Enables extra debug traces. Keep false in production.
ArtifactRequest adds optional session_id and message_id; the response includes paths for query.txt, nlu_result.json, retrieval_result.json, and manifest.json.
NLUResult
Field
Type
Description
query_id
string
UUID shared by NLU and retrieval outputs.
raw_query
string
Original frontend query.
normalized_query
string
Normalized query text.
question_style
enum
fact, why, compare, advice, forecast.
product_type
object
Single-label product prediction with label and score.
Source name, such as cninfo, akshare_sina, or a news outlet.
source_url
Web or PDF URL. Dataset-only notes may use dataset://....
provider
Provider name.
title, summary, text_excerpt, body
Text fields for downstream reading.
body_available
Whether full body text is available.
publish_time, retrieved_at
Time metadata.
entity_hits
Matched symbols or entity names.
retrieval_score, rank_score
Initial and reranked scores.
reason
Ranking reasons.
payload
Optional raw extension object.
Structured Evidence
Field
Description
evidence_id
Unique structured evidence ID.
source_type
Structured source type.
source_name, provider
Source metadata.
source_url
Public page URL when available; API-only rows may keep this null.
provider_endpoint
API/function endpoint, such as akshare.stock_zh_a_hist or tushare.daily.
query_params
Provider query parameters.
source_reference
Traceable reference such as provider://akshare_sina/stock_zh_a_hist.
as_of, period, retrieved_at
Time metadata.
field_coverage
Field completeness summary.
quality_flags
Data quality flags.
payload
Business payload consumed by downstream models.
Source Types
Type
Used In
Meaning
news
documents
News articles from live or local providers.
announcement
documents
Exchange or Cninfo-style public company announcement.
research_note
documents
Research report, analyst note, or research-style dataset document.
faq
documents
Curated FAQ for rules, fees, or product mechanics.
product_doc
documents
Product document or explainer.
market_api
structured
Stock/ETF/fund/index quote or price-history data.
fundamental_sql
structured
Company financial indicators, valuation, profitability, or fundamentals.
industry_sql
structured
Industry identity, sector trend, or sector context.
macro_sql
structured
Macro seed or macro table data.
fund_nav, fund_fee, fund_redemption, fund_profile
structured
Fund and ETF product data.
index_daily, index_valuation
structured
Index quote and valuation data.
macro_indicator, policy_event
structured
Live macro indicators or policy records.
Coverage
Key
Meaning
coverage.price
Price, NAV, or market evidence exists.
coverage.news
At least one news document exists.
coverage.industry
Industry evidence exists.
coverage.fundamentals
Fundamental evidence exists.
coverage.announcement
Announcement evidence exists.
coverage.product_mechanism
FAQ/product/fund mechanism evidence exists.
coverage.macro
Macro or policy evidence exists.
coverage.risk
Risk-relevant evidence exists.
coverage.comparison
Comparison query has evidence for at least two targets.
coverage_detail uses more specific keys such as price_history, financials, valuation, industry_snapshot, fund_nav, fund_fee, fund_redemption, fund_profile, index_daily, index_valuation, macro_indicator, and policy_event.
Warnings and Quality Flags
Field
Value
Meaning
warnings
out_of_scope_query
NLU classified the query as out of scope; retrieval abstained.
warnings
clarification_required_missing_entity
Query needs clarification, usually because an entity is missing or unresolved.
warnings
announcement_not_found_recent_window
Announcements were requested but no recent matching announcement was found.
quality_flags
seed_source
Row came from bundled seed data, not a live provider.
quality_flags
missing_source_url
No public page URL is attached.
quality_flags
empty_payload
No business payload fields are present.
quality_flags
missing_values
At least one business payload field is null.
Ranking Reasons
Current reason values include lexical_score, trigram_similarity, entity_exact_match, alias_match, title_hit, keyword_coverage, intent_compatibility, topic_compatibility, product_type_match, source_credibility, recency_score, is_primary_disclosure, doc_length, time_window_match, and ticker_hit.
Analysis Summary
analysis_summary is built by query_intelligence/retrieval/market_analyzer.py. It summarizes evidence; it is not investment advice.