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 3 |
+
from src.llms.groqllm import GroqLLM
|
| 4 |
+
from langchain_core.messages import HumanMessage, SystemMessage, AIMessage, get_buffer_string
|
| 5 |
+
from src.utils.prompts import clarification_with_user_instructions, transform_messages_into_customer_query_brief_prompt
|
| 6 |
+
from src.states.queryState import SparrowAgentState, ClarifyWithUser, CustomerQuestion # Import from correct module
|
| 7 |
+
from src.utils.utils import get_today_str
|
| 8 |
+
|
| 9 |
+
class QueryNode:
|
| 10 |
+
def __init__(self, llm):
|
| 11 |
+
self.llm = llm
|
| 12 |
+
|
| 13 |
+
def clarify_with_user(self, state: SparrowAgentState) -> SparrowAgentState:
|
| 14 |
+
"""
|
| 15 |
+
Determine if the user's request contains sufficient information to proceed.
|
| 16 |
+
Returns updated state with clarification status.
|
| 17 |
+
"""
|
| 18 |
+
structured_output_model = self.llm.with_structured_output(ClarifyWithUser)
|
| 19 |
+
|
| 20 |
+
try:
|
| 21 |
+
response = structured_output_model.invoke([
|
| 22 |
+
SystemMessage(
|
| 23 |
+
content="Route the input to yes or no based on the need of clarification of the query"
|
| 24 |
+
),
|
| 25 |
+
HumanMessage(
|
| 26 |
+
content=clarification_with_user_instructions.format(
|
| 27 |
+
messages=get_buffer_string(messages=state.get("messages", [])),
|
| 28 |
+
date=get_today_str()
|
| 29 |
+
)
|
| 30 |
+
)
|
| 31 |
+
])
|
| 32 |
+
|
| 33 |
+
print("CLARIFICATION RESPONSE:", response)
|
| 34 |
+
|
| 35 |
+
# Update state based on response
|
| 36 |
+
updated_state = {**state}
|
| 37 |
+
|
| 38 |
+
if response.need_clarification == 'yes':
|
| 39 |
+
updated_state.update({
|
| 40 |
+
"messages": state.get("messages", []) + [AIMessage(content=response.question)],
|
| 41 |
+
"clarification_complete": False,
|
| 42 |
+
"needs_clarification": True
|
| 43 |
+
})
|
| 44 |
+
# Add to notes for routing logic
|
| 45 |
+
updated_state["notes"] = state.get("notes", []) + ["Clarification requested from user"]
|
| 46 |
+
else:
|
| 47 |
+
updated_state.update({
|
| 48 |
+
"messages": state.get("messages", []) + [AIMessage(content=response.verification)],
|
| 49 |
+
"clarification_complete": True,
|
| 50 |
+
"needs_clarification": False
|
| 51 |
+
})
|
| 52 |
+
# Add to notes for routing logic
|
| 53 |
+
updated_state["notes"] = state.get("notes", []) + ["Clarification complete, sufficient information provided"]
|
| 54 |
+
|
| 55 |
+
return updated_state
|
| 56 |
+
|
| 57 |
+
except Exception as e:
|
| 58 |
+
print(f"Error in clarify_with_user: {e}")
|
| 59 |
+
return {
|
| 60 |
+
**state,
|
| 61 |
+
"clarification_complete": False,
|
| 62 |
+
"needs_clarification": True,
|
| 63 |
+
"notes": state.get("notes", []) + [f"Error in clarification: {str(e)}"],
|
| 64 |
+
"error": str(e)
|
| 65 |
+
}
|
| 66 |
+
|
| 67 |
+
def write_query_brief(self, state: SparrowAgentState) -> SparrowAgentState:
|
| 68 |
+
"""
|
| 69 |
+
Transform the conversation history into a comprehensive customer query brief.
|
| 70 |
+
"""
|
| 71 |
+
try:
|
| 72 |
+
# Use the correct CustomerQuestion from queryState
|
| 73 |
+
structured_output_model = self.llm.with_structured_output(CustomerQuestion)
|
| 74 |
+
|
| 75 |
+
messages = state.get("messages", [])
|
| 76 |
+
print("STATE MESSAGES:", messages)
|
| 77 |
+
|
| 78 |
+
if not messages:
|
| 79 |
+
print("ERROR: No messages in state")
|
| 80 |
+
return {
|
| 81 |
+
**state,
|
| 82 |
+
"query_brief": "",
|
| 83 |
+
"notes": state.get("notes", []) + ["No messages available for query brief creation"],
|
| 84 |
+
"error": "No messages available for query brief creation"
|
| 85 |
+
}
|
| 86 |
+
|
| 87 |
+
# Format the prompt with the current date
|
| 88 |
+
prompt = transform_messages_into_customer_query_brief_prompt.format(
|
| 89 |
+
messages=get_buffer_string(messages),
|
| 90 |
+
date=get_today_str() # Add the missing date parameter
|
| 91 |
+
)
|
| 92 |
+
print("PROMPT:", prompt[:500] + "..." if len(prompt) > 500 else prompt)
|
| 93 |
+
|
| 94 |
+
# Test raw response first for debugging
|
| 95 |
+
try:
|
| 96 |
+
raw_response = self.llm.invoke([HumanMessage(content=prompt)])
|
| 97 |
+
print("RAW MODEL RESPONSE:", raw_response.content[:200] + "..." if len(raw_response.content) > 200 else raw_response.content)
|
| 98 |
+
except Exception as e:
|
| 99 |
+
print(f"Raw response test failed: {e}")
|
| 100 |
+
|
| 101 |
+
# Get structured response
|
| 102 |
+
response = structured_output_model.invoke([
|
| 103 |
+
SystemMessage(content="You are a helpful assistant that creates detailed query briefs based on conversation history."),
|
| 104 |
+
HumanMessage(content=prompt)
|
| 105 |
+
])
|
| 106 |
+
print("STRUCTURED RESPONSE:", response)
|
| 107 |
+
|
| 108 |
+
if response is None:
|
| 109 |
+
print("ERROR: Structured response is None")
|
| 110 |
+
return {
|
| 111 |
+
**state,
|
| 112 |
+
"query_brief": "",
|
| 113 |
+
"notes": state.get("notes", []) + ["Failed to generate structured response"],
|
| 114 |
+
"error": "Failed to generate structured response"
|
| 115 |
+
}
|
| 116 |
+
|
| 117 |
+
# Validate that we got a proper query brief
|
| 118 |
+
query_brief = getattr(response, 'query_brief', '') or ''
|
| 119 |
+
|
| 120 |
+
if not query_brief or len(query_brief.strip()) < 10:
|
| 121 |
+
print(f"ERROR: Query brief too short or empty: '{query_brief}'")
|
| 122 |
+
return {
|
| 123 |
+
**state,
|
| 124 |
+
"query_brief": "",
|
| 125 |
+
"notes": state.get("notes", []) + ["Generated query brief was too short or empty"],
|
| 126 |
+
"error": "Generated query brief was insufficient"
|
| 127 |
+
}
|
| 128 |
+
|
| 129 |
+
print(f"SUCCESS: Generated query brief: {query_brief}")
|
| 130 |
+
|
| 131 |
+
return {
|
| 132 |
+
**state,
|
| 133 |
+
"query_brief": query_brief,
|
| 134 |
+
"master_messages": [HumanMessage(content=query_brief)],
|
| 135 |
+
"query_brief_complete": True,
|
| 136 |
+
"notes": state.get("notes", []) + ["Query brief successfully created"]
|
| 137 |
+
}
|
| 138 |
+
|
| 139 |
+
except Exception as e:
|
| 140 |
+
print(f"Error in write_query_brief: {e}")
|
| 141 |
+
import traceback
|
| 142 |
+
traceback.print_exc()
|
| 143 |
+
return {
|
| 144 |
+
**state,
|
| 145 |
+
"query_brief": "",
|
| 146 |
+
"notes": state.get("notes", []) + [f"Query brief creation failed: {str(e)}"],
|
| 147 |
+
"error": str(e)
|
| 148 |
+
}
|