backend / agent /tools.py
riosiahaan's picture
Refactor system prompt
20cf130
Raw History Blame Contribute Delete
19.2 kB
import os
import re
import hashlib
import json as json_module
import pandas as pd
# import matplotlib
# matplotlib.use('Agg')
# import matplotlib.pyplot as plt
# import seaborn as sns
from langchain.tools import tool
from langchain_community.utilities import SerpAPIWrapper
from langchain_google_genai import GoogleGenerativeAIEmbeddings
# from langchain_groq import ChatGroq
from langchain_core.prompts import ChatPromptTemplate
# from langchain.chains import create_retrieval_chain
from langchain_classic.chains import create_retrieval_chain
from langchain_classic.chains.combine_documents import create_stuff_documents_chain
from langchain_qdrant import QdrantVectorStore, RetrievalMode
from qdrant_client import QdrantClient
from dotenv import load_dotenv
from pydantic import BaseModel, Field
from langchain_core.embeddings import Embeddings
from langchain_classic.embeddings import CacheBackedEmbeddings
from langchain_community.storage import RedisStore
import redis
load_dotenv()
# ============================================================
# Generic Redis Caching Utilities for Agent Tools
# ============================================================
# Prevents redundant RAG / LLM / Search API usage when the same
# data is requested. Cache key = sha256 of normalized query.
# ============================================================
_CACHE_TTL = 60 * 60 * 48 # 48 hours for general data caching
def _get_redis_client():
"""Get a Redis client for result caching. Returns None if unavailable."""
redis_url = os.getenv("REDIS_URL", "redis://localhost:6379")
try:
client = redis.from_url(redis_url, decode_responses=True)
client.ping()
return client
except Exception as e:
print(f"⚠️ Redis cache unavailable: {e}")
return None
FORMAT_KEYWORDS = ["excel", "xlsx", "download", "unduh", "tabel", "ekspor", "export"]
def _normalize_query(query: str) -> str:
"""Normalize query for consistent cache keys (lowercase, collapse whitespace, strip keywords)."""
q = query.lower().strip()
for kw in FORMAT_KEYWORDS:
q = q.replace(kw, "").strip()
return " ".join(q.split())
def _get_cache_key(prefix: str, query: str) -> str:
"""Generate a stable Redis key from prefix and normalized query."""
return f"{prefix}:{hashlib.md5(_normalize_query(query).encode()).hexdigest()}"
def _get_cached_result(prefix: str, query: str) -> str | None:
"""Check Redis for a cached result. Returns the cached response string or None."""
client = _get_redis_client()
if not client:
return None
try:
key = _get_cache_key(prefix, query)
cached = client.get(key)
if cached:
print(f"βœ… [{prefix.upper()}] Cache HIT for query: '{query[:50]}...'")
return cached
print(f"πŸ” [{prefix.upper()}] Cache MISS for query: '{query[:50]}...'")
return None
except Exception as e:
print(f"⚠️ Error reading config for '{prefix}': {e}")
return None
def _set_cached_result(prefix: str, query: str, result: str) -> None:
"""Store a tool result in Redis with TTL."""
client = _get_redis_client()
if not client:
return
try:
key = _get_cache_key(prefix, query)
client.setex(key, _CACHE_TTL, result)
print(f"πŸ’Ύ [{prefix.upper()}] Result cached for query: '{query[:50]}...'")
except Exception as e:
print(f"⚠️ Error writing cache for '{prefix}': {e}")
# Initialize Qdrant client and vector store globally for efficiency
def get_vector_store():
"""Get or create Qdrant vector store instance."""
client = QdrantClient(
url=os.getenv("QDRANT_URL"),
api_key=os.getenv("QDRANT_API_KEY"),
timeout=60
)
import google.generativeai as genai
# import google.genai as genai
from typing import List
# Custom Embedding Class to ensure output_dimensionality works
class GoogleGenAIEmbeddingsCustom(Embeddings): # Inherit from Embeddings
def __init__(self, api_key, model="models/gemini-embedding-001", output_dimensionality=None):
genai.configure(api_key=api_key)
self.model = model
self.output_dimensionality = output_dimensionality
def embed_documents(self, texts: List[str]) -> List[List[float]]:
return [self.embed_query(text) for text in texts]
def embed_query(self, text: str) -> List[float]:
result = genai.embed_content(
model=self.model,
content=text,
task_type="retrieval_query", # Use retrieval_query for search queries
output_dimensionality=self.output_dimensionality
)
return result['embedding']
embeddings = GoogleGenAIEmbeddingsCustom(
model="models/gemini-embedding-001",
api_key=os.getenv("GOOGLE_API_KEY"),
output_dimensionality=1536
)
redis_url = os.getenv("REDIS_URL", "redis://localhost:6379")
# Setup Embedding Cache
try:
store = RedisStore(redis_url=redis_url, namespace="embedding_cache")
cached_embeddings = CacheBackedEmbeddings.from_bytes_store(
underlying_embeddings=embeddings,
document_embedding_cache=store,
namespace=embeddings.model
)
print(f"βœ… Embedding Cache enabled with Redis at {redis_url}")
except Exception as e:
print(f"⚠️ Redis for Embeddings not available. Using direct embeddings. Error: {e}")
cached_embeddings = embeddings
vector_store = QdrantVectorStore(
client=client,
collection_name="dataset_inda",
embedding=cached_embeddings, # Use the cached wrapper
retrieval_mode=RetrievalMode.DENSE,
# vector_name="dense", # REMOVED: Collection uses unnamed vector
)
return vector_store
# ---------------------------------------------------------------------------
# Context compression helper
# ---------------------------------------------------------------------------
def _compress_rag_context(docs: list, query: str, max_chars: int = 4000) -> str:
"""
Extract only sentences from retrieved chunks that contain at least one
query keyword. Falls back to the full chunk text if nothing matches.
Caps total output at max_chars to keep token count bounded.
"""
# Build a small set of significant query tokens (>3 chars)
tokens = [t.lower() for t in query.split() if len(t) > 3]
selected: list[str] = []
seen: set[str] = set() # deduplicate identical sentences
for doc in docs:
raw = getattr(doc, "page_content", str(doc))
# Split on sentence boundaries (period, newline, semicolon)
sentences = re.split(r'(?<=[.\n;])\s+', raw)
matched: list[str] = []
for sent in sentences:
sent_lower = sent.lower()
if any(tok in sent_lower for tok in tokens):
if sent not in seen:
matched.append(sent.strip())
seen.add(sent)
# If no sentence matched, include first 300 chars of chunk as fallback
if not matched:
fallback = raw[:300]
if fallback not in seen:
selected.append(fallback)
seen.add(fallback)
else:
selected.extend(matched)
compressed = " ".join(selected)
return compressed[:max_chars]
# --- RAG Tool ---
@tool
async def rag_tool(query: str) -> str:
"""Search BPS Kabupaten Flores Timur database for statistical data and answer questions about it."""
try:
# ============================================================
# LAYER 1: Check Redis cache for existing RAG answer
# ============================================================
cached_result = _get_cached_result("rag_tool", query)
if cached_result:
return cached_result
# ============================================================
# LAYER 2: Vector Search + LLM Generation (Cache Miss)
# ============================================================
# Get vector store
vector_store = get_vector_store()
# RAG Context Compression: only top-3 chunks to minimise token usage
retriever = vector_store.as_retriever(
search_type="similarity",
search_kwargs={
"k": 3,
"search_params": {"hnsw_ef": 64}
}
)
prompt_template = """Anda adalah asisten AI BPS Kabupaten Flores Timur.
Gunakan konteks berikut untuk menjawab. Jika data ada, sajikan apa adanya beserta tahun dan wilayah spesifiknya. Jika tidak ada, katakan "Data tidak ditemukan" dan sarankan pencarian lebih spesifik.
Konteks dari database BPS Sumut:
{context}
Pertanyaan: {input}
Jawaban:"""
prompt = ChatPromptTemplate.from_template(prompt_template)
# Initialize LLM using the centralized configuration
from .llm import get_llm, invoke_with_fallback
llm, _ = await get_llm()
# Retrieve raw docs first so we can compress the context
raw_docs = await retriever.ainvoke(query)
compressed_context = _compress_rag_context(raw_docs, query)
# Build a minimal chain using only the compressed context string
from langchain_core.prompts import ChatPromptTemplate as _CPT
compressed_prompt = _CPT.from_template(
prompt_template.replace("{context}", compressed_context)
)
messages = compressed_prompt.format_messages(input=query)
response_msg = await invoke_with_fallback(llm, messages)
# Wrap in a dict that matches the rest of the code
response = {"answer": response_msg.content if hasattr(response_msg, 'content') else str(response_msg),
"context": raw_docs}
# Extract answer
answer = response.get("answer", "Maaf, tidak dapat menghasilkan jawaban.")
# # print(f"DEBUG [rag_tool]: Answer length = {len(answer)}")
# Extract unique table names from context
context_docs = response.get("context", [])
unique_tables = set()
for doc in context_docs:
if hasattr(doc, "metadata") and "tabel" in doc.metadata:
unique_tables.add(doc.metadata["tabel"])
# Format the response with retrieved context info
formatted_answer = answer
if unique_tables:
tables_list = ", ".join(sorted(unique_tables))
formatted_answer += f"\n\nSumber Tabel: {tables_list}"
# Cache the resulting answer
_set_cached_result("rag_tool", query, formatted_answer)
return formatted_answer
except Exception as e:
error_msg = str(e)
# Handle specific errors
if "rate limit" in error_msg.lower() or "quota" in error_msg.lower():
return "Maaf, layanan mencapai batas penggunaan. Silakan coba lagi dalam beberapa saat."
elif "connection" in error_msg.lower() or "timeout" in error_msg.lower():
return "Maaf, tidak dapat terhubung ke database. Silakan coba lagi."
else:
return f"Maaf, terjadi kesalahan saat memproses pertanyaan: {error_msg}"
# --- RAG Excel Tool ---
@tool
async def rag_excel_tool(query: str) -> str:
"""Export BPS Flores Timur statistical data to an Excel file. Use ONLY when user explicitly asks to download, export, or save to Excel."""
try:
import json
import re
# ============================================================
# LAYER 1: Check Redis cache for existing export
# ============================================================
# If the same query was exported before (within 48h), skip
# the entire RAG+LLM+Upload pipeline and return cached URL.
cached_result = _get_cached_result("excel_export", query)
if cached_result:
return cached_result + "\n\n_(πŸ“¦ dari cache, file yang sama sudah pernah digenerate sebelumnya)_"
# ============================================================
# LAYER 2: Full RAG + LLM Pipeline (cache miss)
# ============================================================
# Get vector store
vector_store = get_vector_store()
# RAG Context Compression: top-5 chunks for excel (need more rows)
retriever = vector_store.as_retriever(
search_type="similarity",
search_kwargs={
"k": 5,
"search_params": {"hnsw_ef": 64}
}
)
# Improved prompt specifically designed for Tabular Data Extraction
prompt_template = """Ekstrak SEMUA data numerik dari konteks ke JSON array. Output JSON saja, tanpa teks lain.
Format kolom: "Periode", "Lokasi", "Jumlah" (numerik, tanpa pemisah ribuan), "Satuan"
Urutkan: Periode terlama ke terbaru. Maks 100 baris.
Konteks: {context}
Permintaan: {input}
Contoh:
[{{"Periode":"2022","Lokasi":"Flores Timur","Jumlah":12345,"Satuan":"orang"}}]
JSON:"""
prompt = ChatPromptTemplate.from_template(prompt_template)
# Initialize LLM using the centralized configuration
from .llm import get_llm, invoke_with_fallback
llm, _ = await get_llm()
# 1. Retrieve
raw_docs = await retriever.ainvoke(query)
# 2. Format Context
context_str = "\n\n".join([getattr(doc, "page_content", str(doc)) for doc in raw_docs])
# 3. Format messages and invoke LLM
messages = prompt.format_messages(context=context_str, input=query)
response_msg = await invoke_with_fallback(llm, messages)
answer = response_msg.content if hasattr(response_msg, 'content') else str(response_msg)
# Clean up the answer to extract JSON
json_str = ""
# 1. Try to find JSON within markdown code blocks
code_block_match = re.search(r'```(?:json)?\s*(\[.*?\])\s*```', answer, re.DOTALL)
if code_block_match:
json_str = code_block_match.group(1)
else:
# 2. Fallback: Find the first outer bracket pair
json_match = re.search(r'\[.*\]', answer, re.DOTALL)
if json_match:
json_str = json_match.group(0)
if not json_str:
return "Maaf, gagal mengekstrak format data tabel. LLM tidak menghasilkan JSON array yang valid."
try:
# Attempt to parse
data_list = json.loads(json_str)
except json.JSONDecodeError as e:
return "Maaf, format data yang dihasilkan tidak valid (JSON Error)."
if not data_list:
return "Maaf, tidak ditemukan data yang cukup spesifik untuk dibuatkan tabel Excel. Coba query yang lebih detail."
# Convert to DataFrame
df = pd.DataFrame(data_list)
# Generate filename
timestamp = pd.Timestamp.now().strftime('%Y%m%d%H%M%S')
clean_query = "".join(c for c in query if c.isalnum() or c in (' ','_')).replace(' ','_')[:30]
filename = f"export_{clean_query}_{timestamp}.xlsx"
# --- SUPABASE UPLOAD LOGIC ---
try:
from supabase import create_client, Client
import io
# Initialize Supabase
supabase_url = os.getenv("SUPABASE_URL")
supabase_key = os.getenv("SUPABASE_KEY")
bucket_name = "exports" # Pastikan bucket ini ada di Supabase dan Public
if not supabase_url or not supabase_key:
raise ValueError("Supabase credentials not set")
supabase: Client = create_client(supabase_url, supabase_key)
# Save to buffer (memory) instead of disk
output = io.BytesIO()
with pd.ExcelWriter(output, engine='xlsxwriter') as writer:
df.to_excel(writer, index=False)
output.seek(0)
# Upload to Supabase
res = supabase.storage.from_(bucket_name).upload(
path=filename,
file=output.read(),
file_options={"content-type": "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet"}
)
# Get Public URL
public_url = supabase.storage.from_(bucket_name).get_public_url(filename)
result_msg = f"βœ… Data berhasil diexport ke Excel!\n\nπŸ“₯ [Download File Excel]({public_url})\nπŸ“Š Jumlah Baris: {len(df)}\nπŸ“‘ Kolom: {', '.join(df.columns)}"
# ============================================================
# CACHE the successful result in Redis
# ============================================================
_set_cached_result("excel_export", query, result_msg)
return result_msg
except Exception as upload_error:
# Fallback to local save
output_dir = "static/exports"
os.makedirs(output_dir, exist_ok=True)
filepath = os.path.join(output_dir, filename)
df.to_excel(filepath, index=False)
return f"βœ… Data berhasil diexport ke Excel (Local)!\n\nπŸ“‚ File: {filepath}\nπŸ“Š Jumlah Baris: {len(df)}\nπŸ“‘ Kolom: {', '.join(df.columns)}"
except Exception as e:
return f"Error creating Excel: {str(e)}"
# --- Search Tool ---
@tool
async def search_tool(query: str):
"""Search the web for BPS Flores Timur general info (office address, news, contacts) not found in the database."""
try:
# Check cache first
cached_result = _get_cached_result("search_tool", query)
if cached_result:
return cached_result
search = SerpAPIWrapper()
# Use .results() to get the raw JSON response
results = search.results(query)
# Check if organic results exist
if "organic_results" not in results:
return "Maaf, tidak ditemukan hasil pencarian yang relevan."
# Format the top 5 results with links
formatted_results = "Berikut hasil pencarian yang ditemukan:\n\n"
for item in results["organic_results"][:5]:
title = item.get("title", "No Title")
link = item.get("link", "#")
snippet = item.get("snippet", "No description available.")
# Format as Markdown link with description
formatted_results += f"### [{title}]({link})\n"
formatted_results += f"{snippet}\n\n"
# Cache the resulting search output
_set_cached_result("search_tool", query, formatted_results)
return formatted_results
except Exception as e:
return f"Error in Search tool: {str(e)}"
tools = [rag_tool, rag_excel_tool, search_tool]