Inferensys

Prompt

Multi-Tenant Query Rewriting Prompt with Tenant Context

A practical prompt playbook for using Multi-Tenant Query Rewriting Prompt with Tenant Context in production AI workflows.
Wide-angle shot of a modern WeWork open floor plan with creative walls covered in AI system architecture diagrams, product team collaborating in standing desk area with industrial lighting.
PROMPT PLAYBOOK

When to Use This Prompt

Understand the core job of multi-tenant query rewriting, the required context, and when this approach is the right fit versus when simpler alternatives suffice.

This prompt is designed for SaaS platform teams operating a shared Retrieval Augmented Generation (RAG) infrastructure that serves multiple tenants. The primary job-to-be-done is to rewrite a user's natural language query before it reaches a vector or keyword index, injecting tenant-specific terminology, data scope boundaries, and access policies. The goal is to ensure that retrieval is strictly confined to the correct tenant partition, preventing cross-tenant data leakage at the retrieval layer. This is critical when a generic query like 'show me the Q3 revenue report' must resolve to entirely different documents for Tenant A versus Tenant B, based on their isolated data stores within the same physical index.

You should use this prompt when tenant isolation cannot be guaranteed solely by pre-filtering metadata at the database level. If your vector database applies a tenant ID filter after a semantic search, the query itself might still pull irrelevant or neighboring tenant vectors into the top-K candidate set, wasting compute and risking leakage. This prompt solves that by making the query semantically specific to the tenant's domain before it's embedded. For example, it can expand 'Q3 report' to 'Q3 2024 financial performance report for [Tenant A's Product Line]' using a tenant-specific glossary, ensuring the embedding is closer to the correct document cluster. Do not use this prompt for single-tenant applications where the entire index belongs to one organization, or when tenant context is already perfectly enforced by row-level security in a structured database without any need for semantic scoping on the query side.

Before implementing this prompt, you must have a reliable mechanism to inject the correct tenant context at runtime. This means your application middleware must resolve the user's identity to a tenant_id and fetch the corresponding tenant profile—including a terminology glossary, data scope rules, and access policies—before assembling the prompt. A failure to provide this context will result in a generic rewrite that fails to isolate tenants. Next, proceed to the prompt template to see how these dynamic inputs are structured, and then review the implementation harness to understand how to validate the rewritten query for tenant isolation before it is executed against your retrieval index.

PRACTICAL GUARDRAILS

Use Case Fit

Where the Multi-Tenant Query Rewriting Prompt delivers value and where it introduces risk. Use these cards to decide if this pattern fits your retrieval architecture.

01

Good Fit: SaaS Platforms with Strict Data Partitioning

Use when: your application serves multiple organizations where documents must never leak across tenant boundaries. The prompt injects tenant-specific terminology and scope constraints directly into the rewritten query. Guardrail: Always pair with a deterministic access-control filter at the retrieval layer—never rely on the prompt alone for tenant isolation.

02

Bad Fit: Single-Tenant or Open Corpus Applications

Avoid when: all users share the same document corpus with no tenant partitioning. The overhead of tenant-context injection adds latency and prompt complexity without benefit. Guardrail: Use simpler query rewriting prompts from the synonym expansion or intent-driven reformulation playbooks instead.

03

Required Input: Tenant Context Object

What to watch: The prompt requires a structured tenant context including tenant ID, allowed document scopes, tenant-specific terminology mappings, and access policies. Missing or incomplete tenant context produces either over-restricted or leaky queries. Guardrail: Validate the tenant context object before prompt assembly—reject rewrites if tenant scope is undefined or empty.

04

Operational Risk: Cross-Tenant Terminology Leakage

What to watch: When tenant-specific terminology overlaps across tenants, the rewritten query may inject terms that inadvertently broaden retrieval scope beyond the intended partition. Guardrail: Implement post-rewrite validation that checks injected terms against the tenant's approved vocabulary list and strips unapproved expansions before retrieval execution.

05

Operational Risk: Tenant Context Staleness

What to watch: Tenant terminology, access policies, and scope boundaries change over time. A cached or stale tenant context object produces rewrites that reflect outdated permissions. Guardrail: Version tenant context objects with a TTL and re-fetch before each rewrite session. Log the context version in retrieval traces for auditability.

06

Bad Fit: Latency-Sensitive Real-Time Search

Avoid when: end-to-end retrieval latency must stay under 100ms and the tenant context assembly plus LLM rewrite adds unacceptable overhead. Guardrail: For low-latency paths, precompute tenant-specific query templates or use deterministic filter injection rather than LLM-based rewriting at query time.

PROMPT PLAYBOOK

Copy-Ready Prompt Template

A reusable prompt that rewrites user queries for tenant-isolated retrieval by injecting tenant-specific terminology, data scope boundaries, and access policies.

This prompt template is the core instruction set for a multi-tenant query rewriting system. It takes a raw user query and a structured tenant context object and produces a rewritten query that is safe to execute against a tenant-partitioned retrieval index. The prompt enforces tenant isolation by explicitly binding the rewrite to the tenant's allowed data scopes, terminology, and access policies. Use this template as a starting point; you will need to replace each square-bracket placeholder with live data from your tenant context service before sending the request to the model.

text
You are a query rewriting agent for a multi-tenant SaaS platform. Your job is to rewrite a user's query so that retrieval stays strictly within the correct tenant partition. You must inject tenant-specific terminology, enforce data scope boundaries, and apply tenant-level access policies.

## Tenant Context
- Tenant ID: [TENANT_ID]
- Tenant Name: [TENANT_NAME]
- Allowed Data Scopes: [ALLOWED_DATA_SCOPES]
- Denied Data Scopes: [DENIED_DATA_SCOPES]
- Tenant-Specific Terminology: [TENANT_TERMINOLOGY_MAP]
- Access Policies: [ACCESS_POLICIES]
- User Role within Tenant: [USER_ROLE]
- User Permissions: [USER_PERMISSIONS]

## Original User Query
[USER_QUERY]

## Rewriting Rules
1. Replace any generic terms with the tenant-specific equivalents from the Tenant-Specific Terminology map. Do not invent new terms.
2. Add explicit scope constraints to the query so that retrieval only considers documents within the Allowed Data Scopes. If the original query implies a scope outside the allowed list, narrow it to the closest allowed scope.
3. Remove or rewrite any query component that would require access to a Denied Data Scope. If the entire query targets a denied scope, output an empty query and set `blocked: true`.
4. Apply the Access Policies to determine if the user's role and permissions allow the requested information. If the policy denies access, output an empty query and set `blocked: true`.
5. Preserve the user's original intent as much as possible while enforcing the above rules.
6. Do not add information that is not present in the Tenant Context or the Original User Query.

## Output Format
Return a valid JSON object with the following schema:
{
  "rewritten_query": "string (the rewritten query, or empty string if blocked)",
  "blocked": boolean,
  "blocked_reason": "string (explanation if blocked, otherwise null)",
  "applied_terminology": ["string (list of tenant terms injected)"],
  "applied_scopes": ["string (list of allowed scopes applied)"],
  "warnings": ["string (any concerns about the rewrite, e.g., ambiguous scope mapping)"]
}

## Examples
[FEW_SHOT_EXAMPLES]

## Constraints
[CONSTRAINTS]

To adapt this template, start by wiring your tenant context resolution service to populate the placeholders. The [TENANT_TERMINOLOGY_MAP] should be a JSON object mapping generic terms to tenant-specific equivalents, sourced from the tenant's configuration. The [ALLOWED_DATA_SCOPES] and [DENIED_DATA_SCOPES] should be explicit lists of document partitions, tags, or namespaces. The [FEW_SHOT_EXAMPLES] placeholder is critical for teaching the model the expected behavior—include at least one example of a normal rewrite, one example of a blocked query due to scope violation, and one example of terminology injection. The [CONSTRAINTS] placeholder can be used to add additional rules, such as maximum query length or required output language. After populating the template, validate the model's output against the expected JSON schema before forwarding the rewritten query to your retrieval system. If the blocked field is true, log the blocked_reason and return a controlled empty result set to the user rather than executing any retrieval.

IMPLEMENTATION TABLE

Prompt Variables

Inputs the prompt needs to work reliably. Validate each before assembly to prevent tenant leakage and malformed queries.

PlaceholderPurposeExampleValidation Notes

[USER_QUERY]

The raw natural language question from the user

Show me Q3 revenue reports for Acme Corp

Must be non-empty string. Reject null or whitespace-only input before prompt assembly.

[TENANT_ID]

Unique identifier for the tenant partition

tenant_acme_corp_prod

Must match tenant registry pattern. Validate against active tenant list. Reject unknown or suspended tenants.

[TENANT_TERMINOLOGY]

Tenant-specific terms, acronyms, and entity names to inject into the rewrite

{"revenue": "ARR", "Q3": "FY24-Q3", "Acme Corp": "ACME"}

Must be valid JSON object. Validate keys are lowercase. Null allowed if tenant has no custom terminology.

[TENANT_DATA_SCOPE]

Document scopes, collections, or indexes the tenant is authorized to access

["acme_finance", "acme_reports_v2"]

Must be non-empty array of strings. Validate each scope exists in index registry. Reject if any scope maps to another tenant's partition.

[TENANT_ACCESS_POLICY]

Structured access rules defining what the tenant can retrieve

{"max_classification": "internal", "allowed_departments": ["finance", "exec"]}

Must be valid JSON with required fields. Validate classification levels against data catalog. Reject if policy allows cross-tenant access.

[USER_ROLE]

The requesting user's role within the tenant for fine-grained access

finance_analyst

Must match role enum defined in tenant config. Validate role is active for this tenant. Null allowed for tenant-level queries without user differentiation.

[OUTPUT_SCHEMA]

Expected JSON structure for the rewritten query output

{"rewritten_query": "string", "applied_terms": ["string"], "scope_filters": ["string"]}

Must be valid JSON Schema. Validate required fields include rewritten_query and scope_filters. Reject schemas missing tenant isolation fields.

[MAX_TERM_EXPANSION]

Upper limit on number of tenant-specific terms to inject

5

Must be positive integer between 1 and 10. Validate range before prompt assembly. Prevents over-expansion that dilutes original query intent.

PROMPT PLAYBOOK

Implementation Harness Notes

How to wire the multi-tenant query rewriting prompt into a production RAG application with tenant isolation, validation, and observability.

This prompt is not a standalone chatbot. It is a pre-retrieval transformation step that must sit between the user's raw query and the retrieval engine. The application layer is responsible for injecting the correct tenant context, validating the rewritten query against tenant boundaries, and logging every transformation for auditability. The prompt's job is to produce a rewritten query and a set of explicit tenant-scope constraints; the harness's job is to enforce those constraints before any document is retrieved.

Wiring the prompt into a retrieval pipeline requires a strict execution order. First, resolve the tenant identifier from the authenticated session or API key—never from user input. Second, fetch the tenant's configuration object, which must include tenant_id, allowed_document_scopes, tenant_terminology, and access_policies. Third, assemble the prompt with the raw user query, the tenant context, and the output schema. Fourth, parse the model's JSON response and validate that every scope constraint in the output maps to an allowed scope in the tenant configuration. Reject any rewritten query that introduces a scope not present in the tenant's allow-list. Fifth, pass the validated rewritten query and scope filters to the retrieval engine. Retries and fallbacks: if the model returns malformed JSON, retry once with a stricter schema reminder. If the rewritten query contains disallowed scopes, log the violation, strip the offending constraints, and fall back to a tenant-scoped keyword search. Do not retry scope violations—they indicate a prompt or tenant config issue that needs human review.

Model choice and tool use matter here. This prompt works best with models that have strong instruction-following and JSON output capabilities (GPT-4o, Claude 3.5 Sonnet, or equivalent). Avoid smaller models that may hallucinate tenant terminology or ignore scope constraints. This prompt should not call external tools or APIs—it is a pure text-to-JSON transformation. If your retrieval engine requires tool calls for filter construction, perform the tool call in the harness after validating the prompt's output, not inside the prompt itself. Observability: log the raw user query, the tenant ID, the full rewritten query, the scope constraints, and a hash of the tenant configuration version. This audit trail is essential for debugging cross-tenant leakage incidents and for demonstrating compliance during security reviews. Human review is not required for every query, but you should implement a monitoring alert that triggers when a rewritten query is rejected for scope violations or when the model's output deviates from the expected schema more than 5% of the time in a rolling window.

What to avoid: never pass the tenant configuration as a raw user input or allow the user to specify their own tenant ID. Never skip the scope validation step—even if the model has been reliable in testing, a single hallucinated scope can cause a cross-tenant data leak. Never use this prompt without versioning both the prompt template and the tenant configuration schema; a mismatch between the two will produce silent failures. Finally, do not treat this prompt as a security boundary on its own. The retrieval engine must enforce tenant isolation at the index or database level. The prompt is a query transformation aid, not an access control mechanism.

IMPLEMENTATION TABLE

Expected Output Contract

Defines the required JSON structure, field types, and validation rules for the multi-tenant query rewriting prompt response. Use this contract to parse, validate, and route the LLM output before executing retrieval.

Field or ElementType or FormatRequiredValidation Rule

rewritten_query

string

Must contain tenant-specific terminology from [TENANT_GLOSSARY]. Must not exceed 300 characters. Parse check: non-empty, no unresolved placeholders.

tenant_id

string

Must exactly match the [TENANT_ID] input value. Schema check: string equality comparison. Failure triggers a retry with explicit tenant constraint.

scope_filters

object

Must include a 'partition_key' field matching [TENANT_PARTITION_KEY]. All filter values must be drawn from [TENANT_ACCESS_POLICIES]. Schema check: JSON Schema validation against expected filter shape.

scope_filters.partition_key

string

Must equal the value of [TENANT_PARTITION_KEY]. Parse check: exact string match. A mismatch is a critical tenant isolation failure.

scope_filters.additional_filters

array

If present, each item must be an object with 'field', 'operator', and 'value' drawn from [TENANT_ACCESS_POLICIES]. Null allowed if no extra filters are needed.

expansion_terms

array of strings

Each term must be present in [TENANT_GLOSSARY] or derived from [TENANT_TERMINOLOGY]. Null allowed. Validation: cross-reference check against allowed term list.

confidence

number

Must be a float between 0.0 and 1.0. Values below [CONFIDENCE_THRESHOLD] should trigger a human review or clarification request. Parse check: numeric range validation.

reasoning

string

Brief explanation of the rewrite logic. Must not exceed 500 characters. Null allowed. If present, must not reference other tenants or cross-tenant data.

PRACTICAL GUARDRAILS

Common Failure Modes

What breaks first when rewriting queries with tenant context and how to prevent cross-tenant leakage, scope drift, and silent authorization failures.

01

Tenant Context Omission

What to watch: The model rewrites the query without injecting the tenant identifier, causing retrieval to scan across all tenant partitions. Guardrail: Require the tenant ID as a mandatory input variable and prepend it to every rewritten query. Validate that the tenant ID appears in the output before retrieval execution.

02

Cross-Tenant Terminology Leakage

What to watch: The model injects terminology or entity names from one tenant's glossary into a query for a different tenant, causing incorrect retrieval results. Guardrail: Provide only the current tenant's terminology map in the prompt context. Never include multiple tenant glossaries in the same prompt call. Log and audit injected terms against the tenant's approved vocabulary.

03

Scope Boundary Drift

What to watch: The rewritten query broadens the retrieval scope beyond the tenant's authorized data partition, such as removing a required filter or generalizing a tenant-specific constraint. Guardrail: Append non-negotiable scope constraints as a post-processing step outside the model. Use a deterministic filter merge that the model cannot override, and test with queries designed to probe boundary edges.

04

Silent Tenant Context Substitution

What to watch: The model hallucinates or substitutes a different tenant context when the provided context is sparse or ambiguous, leading to queries that retrieve another tenant's data. Guardrail: Include explicit negative instructions: 'If tenant context is missing or ambiguous, return an error flag instead of guessing.' Add a pre-retrieval check that halts execution if the tenant ID in the output does not match the input.

05

Metadata Filter Stripping

What to watch: The model drops or ignores tenant-specific metadata filters during query expansion, causing the retrieval engine to ignore partition keys. Guardrail: Separate query expansion from filter construction. Generate the rewritten query text and the metadata filter clause as distinct output fields. Apply filters at the retrieval layer, not inside the rewritten query string.

06

Multi-Tenant Prompt Contamination

What to watch: Reusing a shared prompt template across tenants without isolating tenant-specific instructions causes the model to blend policies or terminology from multiple tenants. Guardrail: Treat the tenant context injection as a parameterized template fill, not a shared conversation history. Use separate prompt instances per tenant request. Never cache or reuse model responses across tenants.

IMPLEMENTATION TABLE

Evaluation Rubric

Run these checks against a golden dataset of tenant-query pairs to validate tenant isolation, term injection, and scope boundary enforcement before shipping the prompt.

CriterionPass StandardFailure SignalTest Method

Tenant Isolation

Rewritten query contains only terms, entities, and scope constraints from the target [TENANT_CONTEXT]

Cross-tenant terminology, entity IDs, or data scope boundaries from another tenant appear in the output

Run golden dataset queries across multiple tenants; assert zero cross-tenant term leakage using substring match against other tenant context blocks

Tenant Terminology Injection

At least one tenant-specific synonym or canonical term from [TENANT_CONTEXT] is injected when the user query uses a generic equivalent

Generic user terms pass through unchanged when a tenant-specific term exists in the context

Compare rewritten query terms against [TENANT_CONTEXT] terminology map; flag missing injections for terms with known tenant equivalents

Scope Boundary Adherence

All generated metadata filters, date ranges, or partition keys fall within the tenant's authorized data scope

A filter clause references a partition, project, or data boundary outside [TENANT_CONTEXT] scope definition

Parse output for filter clauses; validate each scope value against the tenant's allowed scope list in the golden dataset

Original Intent Preservation

The core information need from [USER_QUERY] is preserved after tenant term injection and scope constraint addition

The rewritten query changes the semantic intent or adds constraints that exclude relevant in-tenant documents

Human review or LLM judge compares original query intent with rewritten query; flag intent drift when semantic similarity drops below threshold

Permission Boundary Enforcement

No query component requests or implies access to document scopes outside the tenant's explicit permission set

Generated query includes terms like 'all tenants', 'cross-tenant', or references to tenant IDs not in the authorized list

Scan output for unauthorized tenant identifiers and scope-escalation language; assert zero matches against deny-list patterns

Metadata Filter Correctness

All extracted metadata constraints from [USER_QUERY] are merged with tenant default filters without conflict or duplication

Conflicting filter values appear (e.g., date range outside tenant data window) or duplicate clauses bloat the query

Parse the filter block; check for logical conflicts using constraint solver or rule-based validator; flag overlapping or contradictory clauses

Empty Context Handling

When [TENANT_CONTEXT] is empty or missing, the prompt falls back to a safe default scope or returns an error without fabricating tenant terms

The prompt hallucinates tenant terminology, scope constraints, or filter values when no context is provided

Test with null or empty [TENANT_CONTEXT]; assert output contains no invented tenant-specific terms and either returns error or generic query

Output Schema Compliance

Output matches the defined [OUTPUT_SCHEMA] with all required fields present and correctly typed

Missing required fields, extra fields, or type mismatches in the structured output

Validate output against JSON Schema; flag any schema violations including missing required fields, wrong types, or unexpected properties

ADAPTATION OPTIONS

Adapt This Prompt

How to adapt

Add a strict JSON output schema with rewritten_query, injected_terms, and scope_constraints_applied fields. Validate the schema before retrieval. Log the tenant ID, original query, and rewritten query for audit trails. Add retry logic with a correction prompt if validation fails.

json
{
  "rewritten_query": "string",
  "injected_terms": ["term1"],
  "scope_constraints_applied": ["scope1"],
  "tenant_id": "[TENANT_ID]"
}

Watch for

  • Silent format drift when models change
  • Scope constraints that are too broad or too narrow
  • Missing human review for high-risk tenant boundaries
Prasad Kumkar

About the author

Prasad Kumkar

CEO & MD, Inference Systems

Prasad Kumkar is the CEO & MD of Inference Systems and writes about AI systems architecture, LLM infrastructure, model serving, evaluation, and production deployment. Over 5+ years, he has worked across computer vision models, L5 autonomous vehicle systems, and LLM research, with a focus on taking complex AI ideas into real-world engineering systems.

His work and writing cover AI systems, large language models, AI agents, multimodal systems, autonomous systems, inference optimization, RAG, evaluation, and production AI engineering.