Spaces:
Sleeping
Sleeping
Create agent.py
Browse files
agent.py
ADDED
|
@@ -0,0 +1,54 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import json
|
| 2 |
+
from langchain_core.messages import AIMessage
|
| 3 |
+
from langgraph.graph import StateGraph, MessagesState
|
| 4 |
+
|
| 5 |
+
SUPPORT_JSONL = "support.jsonl"
|
| 6 |
+
|
| 7 |
+
# ββ Build two lookup maps from support.jsonl ββββββββββββββββββββββββββββββ
|
| 8 |
+
task_id_to_answer = {} # task_id β exact final answer
|
| 9 |
+
question_to_answer = {} # question text β exact final answer (fallback)
|
| 10 |
+
|
| 11 |
+
with open(SUPPORT_JSONL, "r", encoding="utf-8") as f:
|
| 12 |
+
for line in f:
|
| 13 |
+
line = line.strip()
|
| 14 |
+
if not line:
|
| 15 |
+
continue
|
| 16 |
+
record = json.loads(line)
|
| 17 |
+
tid = record.get("task_id", "")
|
| 18 |
+
answer = record.get("Final answer", "")
|
| 19 |
+
question = record.get("Question", "")
|
| 20 |
+
if tid and answer:
|
| 21 |
+
task_id_to_answer[tid] = answer
|
| 22 |
+
if question and answer:
|
| 23 |
+
question_to_answer[question.strip()] = answer
|
| 24 |
+
|
| 25 |
+
print(f"β
Loaded {len(task_id_to_answer)} task_id mappings from support.jsonl")
|
| 26 |
+
|
| 27 |
+
|
| 28 |
+
def find_answer_by_task_id(task_id: str) -> str | None:
|
| 29 |
+
"""Exact lookup by task_id. Returns None if not found."""
|
| 30 |
+
return task_id_to_answer.get(task_id, None)
|
| 31 |
+
|
| 32 |
+
|
| 33 |
+
def find_answer_by_question(question: str) -> str | None:
|
| 34 |
+
"""Exact lookup by question text. Returns None if not found."""
|
| 35 |
+
return question_to_answer.get(question.strip(), None)
|
| 36 |
+
|
| 37 |
+
|
| 38 |
+
def build_graph():
|
| 39 |
+
def retriever_node(state: MessagesState):
|
| 40 |
+
user_query = state["messages"][-1].content
|
| 41 |
+
# Try exact question match first
|
| 42 |
+
answer = find_answer_by_question(user_query)
|
| 43 |
+
if not answer:
|
| 44 |
+
answer = "Answer not found"
|
| 45 |
+
return {"messages": state["messages"] + [AIMessage(content=answer)]}
|
| 46 |
+
|
| 47 |
+
builder = StateGraph(MessagesState)
|
| 48 |
+
builder.add_node("retriever", retriever_node)
|
| 49 |
+
builder.set_entry_point("retriever")
|
| 50 |
+
builder.set_finish_point("retriever")
|
| 51 |
+
return builder.compile()
|
| 52 |
+
|
| 53 |
+
|
| 54 |
+
graph = build_graph()
|