Views
No views yet

How can artificial intelligence be utilized to improve emergency response systems in urban environments?
1<query_analysis>
2 <domain ambiguous="false">
3 <candidate confidence="1.0">Technology</candidate>
4 </domain>
5 <intent ambiguous="false">
6 <candidate confidence="1.0">Improving emergency response systems</candidate>
7 </intent>
8 <concepts>
9 <explicit>artificial intelligence, emergency response systems, urban environments</explicit>
10 <implicit>smart city, predictive analytics, data-driven decision making</implicit>
11 </concepts>
12 <relations>
13 <relation subject="artificial intelligence" predicate="utilized to" object="improve emergency response systems"/>
14 <relation subject="emergency response systems" predicate="in" object="urban environments"/>
15 </relations>
16 <insufficient_context>false</insufficient_context>
17 <rephrased>true</rephrased>
18 <rephrased_query>how artificial intelligence can be used to enhance emergency response capabilities in urban areas</rephrased_query>
19</query_analysis>How have its fiscal policies regarding these things impacted its overall financial stability and future outlook, particularly concerning external market fluctuations?
1<query_analysis>
2 <domain ambiguous="true">
3 <candidate confidence="0.6">Economics</candidate>
4 <candidate confidence="0.4">Finance</candidate>
5 </domain>
6 <intent ambiguous="true">
7 <candidate confidence="0.7">Analysis</candidate>
8 <candidate confidence="0.3">Comparison</candidate>
9 </intent>
10 <concepts>
11 <explicit>fiscal policies, external market fluctuations, financial stability, future outlook</explicit>
12 <implicit>[ENTITY], economic factors</implicit>
13 </concepts>
14 <relations>
15 <relation subject="[ENTITY]" predicate="has" object="fiscal policies"/>
16 <relation subject="[ENTITY]" predicate="impacts" object="financial stability"/>
17 <relation subject="[ENTITY]" predicate="impacts" object="future outlook"/>
18 <relation subject="[ENTITY]" predicate="causes" object="external market fluctuations"/>
19 </relations>
20 <insufficient_context>false</insufficient_context>
21 <rephrased>true</rephrased>
22 <rephrased_query>impact of [ENTITY]'s fiscal policies on financial stability and future outlook, particularly due to external market volatility</rephrased_query>
23</query_analysis>How does she describe her emotional journey and the complexities of her interactions with him in that book?
1<query_analysis>
2 <domain ambiguous="true">
3 <candidate confidence="0.5">Literature</candidate>
4 <candidate confidence="0.5">Psychology</candidate>
5 </domain>
6 <intent ambiguous="true">
7 <candidate confidence="0.6">Analysis</candidate>
8 <candidate confidence="0.4">Description</candidate>
9 </intent>
10 <concepts>
11 <explicit>emotional journey, complex interactions</explicit>
12 <implicit>[PERSON], [BOOK]</implicit>
13 </concepts>
14 <relations>
15 <relation subject="[PERSON]" predicate="describes" object="complex emotions"/>
16 <relation subject="[PERSON]" predicate="interacts with" object="him"/>
17 </relations>
18 <insufficient_context>true</insufficient_context>
19 <rephrased>true</rephrased>
20 <rephrased_query>How does [PERSON] describe their emotional journey and the intricacies of their interactions with [PERSON] in the book?</rephrased_query>
21</query_analysis>1.0, properly handling both unambiguous cases (single candidate with confidence 1.0) and ambiguous cases (multiple candidates with distributed confidence). The model can optionally extract explicit and implicit concepts, identify relations between entities using subject-predicate-object triples, and normalize ambiguous terms when disambiguation would improve retrieval.[PERSON] or [COMPANY]. Importantly, the model has learned to preserve already-optimal queries unchanged, recognizing when rephrasing would not improve retrieval effectiveness.1<query_analysis>
2 <domain ambiguous="true|false">
3 <candidate confidence="X.X">...</candidate>
4 </domain>
5 <intent ambiguous="true|false">
6 <candidate confidence="X.X">...</candidate>
7 </intent>
8 <!-- Optional sections -->
9 <concepts>
10 <explicit>...</explicit>
11 <implicit>...</implicit>
12 </concepts>
13 <relations>
14 <relation subject="..." predicate="..." object="..."/>
15 </relations>
16 <normalized_terms>
17 <term original="..." normalized="..."/>
18 </normalized_terms>
19 <!-- End optional sections -->
20 <insufficient_context>true|false</insufficient_context>
21 <rephrased>true|false</rephrased>
22 <rephrased_query>...</rephrased_query>
23</query_analysis>transformers:pip install git+https://github.com/huggingface/transformers.git1SYSTEM_PROMPT = """You are a query analysis and rephraser for a Retrieval-Augmented Generation (RAG) system.
2Your sole task is to **analyze user queries** and output a structured XML document.
3You must **not answer the query itself**, only analyze and rephrase it.
4
5## RAG Query Optimization
6
7Effective rephrasing should optimize for document retrieval by:
8- Using **specific terminology** and domain vocabulary likely to appear in relevant documents
9- **Expanding acronyms** when they add context (but not when the acronym itself is the subject)
10- **Adding disambiguating context** without over-constraining the search
11- **Making implicit references explicit** using placeholders for missing entities (e.g., [PERSON], [COMPANY])
12- **Preserving user intent** while improving retrieval precision
13
14Examples: "How do I reset my password?" → "password reset procedure authentication"
15"What's their revenue?" → "What's [COMPANY]'s revenue?"
16
17## Analysis Process
18
19Follow this systematic approach to decompose each query:
201. **Identify the domain**: Determine the subject area or field the query relates to (e.g., banking, healthcare, technology, legal). Consider both explicit domain indicators and contextual clues.
212. **Determine the intent**: Classify what the user is trying to accomplish (e.g., definition lookup, troubleshooting, comparison, how-to guidance, factual question).
223. **Extract key concepts (optional)**: Identify explicit terms mentioned and relevant implicit concepts that would aid in query understanding.
234. **Identify relations (optional)**: Map out relationships between entities using subject-predicate-object triples when meaningful connections exist.
245. **Normalize terms (optional)**: Disambiguate or standardize ambiguous terms when clarification would improve retrieval (e.g., "Apple" → "Apple Inc." vs "apple fruit").
256. **Assess query quality**: Evaluate if the query has sufficient context for retrieval and whether rephrasing would improve it.
267. **Generate rephrased query**: Create a clearer, more specific version optimized for document retrieval, or keep the original if already optimal.
27
28## Technical Rules
29
301. **Never answer the user's question.** Only analyze and rephrase.
312. Always produce valid XML strictly following the schema below.
323. `<domain>` and `<intent>` are **mandatory** and must contain one or more `<candidate confidence="X.X">...</candidate>` entries:
33 - Confidence scores must always sum to 1.0
34 - If unambiguous: **exactly one candidate** with `confidence="1.0"` and `ambiguous="false"`
35 - If ambiguous: multiple candidates with `ambiguous="true"` and confidence distributed proportionally to plausibility:
36 - Use uniform distribution only when candidates are genuinely equally likely
37 - Otherwise, weight confidence toward the more probable interpretation
38 - Examples:
39 - "What is Mercury's rotation period?" → Astronomy 0.5, Chemistry 0.5 (equally plausible)
40 - "Jaguar speed in the wild" → Zoology 0.8, Automotive 0.2 (context favors animal)
414. Confidence values must always have one decimal place (e.g., `0.5`, `1.0`).
425. Only `<concepts>`, `<relations>`, and `<normalized_terms>` are optional. **All other elements are mandatory.**
436. `<insufficient_context>` and `<rephrased>` must each appear **exactly once** and be either `true` or `false`.
447. `<rephrased_query>` must always appear, even if identical to the input.
458. **Output only valid XML.** Do not include any explanations, comments, or text outside the XML structure.
469. All elements must appear in the order specified in the schema:
47 `<domain> → <intent> → <concepts> → <relations> → <normalized_terms> → <insufficient_context> → <rephrased> → <rephrased_query>`.
48
49## Output Schema
50
51```xml
52<query_analysis>
53 <domain ambiguous="true|false">
54 <candidate confidence="X.X">...</candidate>
55 </domain>
56 <intent ambiguous="true|false">
57 <candidate confidence="X.X">...</candidate>
58 </intent>
59 <!-- Optional sections -->
60 <concepts>
61 <explicit>...</explicit>
62 <implicit>...</implicit>
63 </concepts>
64 <relations>
65 <relation subject="..." predicate="..." object="..."/>
66 </relations>
67 <normalized_terms>
68 <term original="..." normalized="..."/>
69 </normalized_terms>
70 <!-- End optional sections -->
71 <insufficient_context>true|false</insufficient_context>
72 <rephrased>true|false</rephrased>
73 <rephrased_query>...</rephrased_query>
74</query_analysis>
75```"""1from transformers import AutoTokenizer, AutoModelForCausalLM
2
3model_name = "krogoldAI/QueryRefiner-0.5B-v0.1-SFT"
4tokenizer = AutoTokenizer.from_pretrained(model_name)
5model = AutoModelForCausalLM.from_pretrained(model_name)
6
7user_query = "How do I reset my password?"
8
9messages = [
10 {"role": "system", "content": SYSTEM_PROMPT},
11 {"role": "user", "content": user_query}
12]
13
14input_text = tokenizer.apply_chat_template(messages, tokenize=False, add_generation_prompt=True)
15inputs = tokenizer(input_text, return_tensors="pt")
16
17outputs = model.generate(**inputs, temperature=0.7, max_new_tokens=512)
18analysis = tokenizer.decode(outputs[0], skip_special_tokens=True)
19
20print(analysis)| Metric | Qwen2.5-0.5B-Instruct | QueryRefiner-0.5B-v0.1-SFT | QueryRefiner-0.5B-v0.1-GRPO |
|---|---|---|---|
| Tag structure | 10.8% | 99.9% | 99.9% |
| XML validity | 41.0% | 99.8% | 99.9% |
| Order | 2.0% | 99.9% | 99.9% |
| Confidence | 3.1% | 99.9% | 99.9% |
| Perfectly structured output | 0.0% | 99.8% | 99.9% |
1.0.| Metric | QueryRefiner-0.5B-v0.1-SFT | QueryRefiner-0.5B-v0.1-GRPO |
|---|---|---|
| Domain accuracy | 98.97 ± 8.43% | 98.95 ± 8.46% |
| Intent accuracy | 98.20 ± 8.84% | 98.75 ± 8.05% |
| Ambiguity assessment | 99.04 ± 6.84% | 99.40 ± 5.79% |
| Rephrasing quality | 88.23 ± 18.20% | 90.33 ± 17.61% |
| Intent preservation | 95.09 ± 15.74% | 96.02 ± 14.72% |
| Follows guidelines | 97.07 ± 13.78% | 97.40 ± 12.20% |
| Overall semantic score | 96.10 ± 9.74% | 96.81 ± 9.18% |
1JUDGE_PROMPT = """You are evaluating query analyses for a RAG system.
2
3### System Requirements
4The analyzer was instructed to optimize queries for document retrieval by:
5- Using **specific terminology** and domain vocabulary likely to appear in relevant documents
6- **Expanding acronyms** when they add context (but not when the acronym itself is the subject)
7- **Adding disambiguating context** without over-constraining the search
8- **Making implicit references explicit** using placeholders for missing entities (e.g., [PERSON], [COMPANY])
9- **Preserving user intent** while improving retrieval precision
10- **Keeping the original query unchanged** if it's already well-optimized for retrieval
11
12### Input
13Original: "{original}"
14Domain: {domain}
15Intent: {intent}
16Rephrased: "{rephrased}"
17
18Note: The [ambiguous] tag indicates the analyzer determined the query has multiple plausible interpretations for that dimension, with confidence distributed across candidates.
19
20### Evaluation Criteria (1-5 scale)
21
221. Domain Accuracy (1=wrong, 3=acceptable, 5=perfect)
23 - Are the domain candidates correct?
24 - Are confidence scores reasonable?
25
262. Intent Accuracy (1=wrong, 3=acceptable, 5=perfect)
27 - Are the intent candidates correct?
28 - Are confidence scores reasonable?
29
303. Ambiguity Assessment (1=wrong, 3=acceptable, 5=perfect)
31 - Is the ambiguity determination appropriate for this query?
32 - If ambiguous: Is the confidence distribution justified?
33 - If clearly unambiguous but marked ambiguous (or vice versa), score ≤2.
34
354. Rephrasing Quality
36 1 = Poor (significantly degraded the query, or completely failed to address clear issues)
37 2 = Suboptimal (minor degradation, or missed an obvious improvement opportunity)
38 3 = Neutral (minor changes with mixed effects)
39 4 = Good improvement, but could be better
40 5 = Optimal outcome (either improved a suboptimal query, or correctly preserved an already-optimal one)
41 (Note: Do not penalize rephrasing for being minimal if the original was already optimal.)
42
435. Intent Preservation (1=lost, 3=mostly preserved, 5=fully preserved)
44 - Focus on meaning fidelity, not retrieval optimization.
45
466. Follows Guidelines (1=violates, 3=mostly follows, 5=perfectly follows)
47 - Check adherence to the RAG optimization principles above.
48
49### Output Format
50{{
51 "domain_accuracy": <1-5>,
52 "intent_accuracy": <1-5>,
53 "ambiguity_assessment": <1-5>,
54 "rephrasing_quality": <1-5>,
55 "intent_preservation": <1-5>,
56 "follows_guidelines": <1-5>,
57 "critical_issue": "<brief description or null>",
58 "usable": <true/false> // true if suitable for RAG use, even if not perfect
59}}
60
61Output only valid JSON. Do not include any explanations, comments, or text outside the JSON structure.
62"""
63