How do I use QueryShield with LlamaIndex NLSQLTableQueryEngine?
LlamaIndex's NLSQLTableQueryEngine and SQLTableRetrieverQueryEngine are text-to-SQL primitives that work well with LlamaIndex's broader RAG stack but lack a real security validator. Drop QueryShield in as a SQL execution wrapper:
from llama_index.core.query_engine import NLSQLTableQueryEngine
from llama_index.core import SQLDatabase
from queryshield.llamaindex import shielded_sql_database
sql_database = shielded_sql_database( engine=create_engine(DB_URI), policy="research-agent", api_key=os.getenv("QUERYSHIELD_API_KEY"), ) query_engine = NLSQLTableQueryEngine( sql_database=sql_database, tables=["papers", "citations"], ) ```
The wrapper intercepts sql_database.run_sql(), validates against the policy, and either approves, rewrites (injecting required predicates), or raises a QueryShieldRejection that LlamaIndex's response-synthesizer can route into a graceful failure message.
For agentic workflows (ReActAgent, OpenAIAgent) calling SQL as one of many tools, register a tool_callback that runs QueryShield before SQL execution — same pattern. Evidence log correlates the LlamaIndex query_id with the QueryShield decision for end-to-end traceability across the RAG + SQL hybrid pipeline.