File size: 1,845 Bytes
b22c324
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
import json
import chromadb
from agentic_workflow.config import LLM_MODEL
from langchain_ollama import ChatOllama
import re
from langchain_core.messages import HumanMessage, SystemMessage

client = chromadb.PersistentClient(path="./chroma_db")
llm = ChatOllama(model=LLM_MODEL, temperature=0)

# intent analysis
def analyse_intent(query: str) -> dict:

    system = """
        You are an intent classifier. Given a user query, return ONLY valid JSON with:
        - "intent": one of "factual", "conversational", "follow_up", "sensitive"
        - "needs_context": true if retrieval from a knowledge base is needed, false otherwise
        - "needs_history": true if this looks like a follow-up to a prior turn, false otherwise
        
        Rules:
        - Greetings / chit-chat → conversational, needs_context: false
        - Questions about facts / documents → factual, needs_context: true
        - "you said earlier" / pronouns like "it" / "that" → follow_up, needs_history: true
        - Personal data, health, finance → sensitive
        Return ONLY the JSON object. No explanation.
        """
    
    response = llm.invoke([
        SystemMessage(content=system),
        HumanMessage(content=query)
    ])
    raw = response.content.strip()
    # Strip markdown fences if present
    raw = re.sub(r"^```(?:json)?\s*|\s*```$", "", raw).strip()

    try:
        parsed = json.loads(raw)
    except json.JSONDecodeError:
        parsed = {}

    return {
        "intent": "factual",
        "needs_context": True,
        "needs_history": False,
        **parsed
    }

# query= "How do I top-up the value of my card when I am abroad"
# trace = []
# intent_result = analyse_intent(query)
# trace.append({
#         "step": "intent_analysis",
#         "result": intent_result
#     })
# print(f"[Intent] {intent_result}")