Customization challenges
You now have a working Text-to-SQL chatbot! Here are some challenges to extend it further and deepen your understanding.
challenge_1.py
python
# Challenge 1: Add a "Query History" Agent
# Store and retrieve previous queries for the session
class AgentState(TypedDict):
# ... existing fields ...
query_history: list # Add this field
def history_agent(state: AgentState) -> AgentState:
"""Store successful queries in history"""
history = state.get("query_history", [])
if state["sql_query"] and not state["error"]:
history.append({
"question": state["question"],
"sql": state["sql_query"],
"timestamp": datetime.now().isoformat()
})
state["query_history"] = history[-10:] # Keep last 10
return stateChallenge: Add query history tracking to your chatbot.
The next challenge tackles a common production concern: avoiding redundant LLM calls for repeated questions. Query caching can save both latency and cost.
challenge_2.py
python
# Challenge 2: Add Query Caching
# Cache repeated queries to avoid redundant LLM calls
from functools import lru_cache
import hashlib
@lru_cache(maxsize=100)
def cached_sql_generation(question_hash: str, question: str) -> str:
"""Cache SQL generation for repeated questions"""
# Your SQL generation logic here
pass
def sql_agent_with_cache(state: AgentState) -> AgentState:
question = state["question"]
question_hash = hashlib.md5(question.lower().encode()).hexdigest()
# Try cache first
cached = cached_sql_generation(question_hash, question)
if cached:
state["sql_query"] = cached
state["sql_reason"] = "Retrieved from cache"
return state
# Otherwise generate new SQL
# ... existing logic ...Challenge: Implement caching for repeated queries.
Hints: Hints
Loading practice…
Validation checklist: Extension ideas explored
Loading practice…
These extensions show how much further you can take the system. The final step is a comprehensive assessment of everything you have learned.