This prompt is designed for AI coding agents that need to translate a natural language intent—such as 'find where authentication logic checks user roles' or 'locate the database migration that added the email column'—into one or more precise, structured search queries. The primary job-to-be-done is bridging the gap between a developer's high-level question and the literal patterns that grep, ripgrep, or AST-based search tools require. The ideal user is an AI engineer or developer building a coding agent that must autonomously explore an unfamiliar repository, locate relevant code, and assemble context before planning an edit.
Prompt
Semantic Search Query Generation Prompt for Codebases

When to Use This Prompt
Define the job, reader, and constraints for the semantic search query generation prompt.
Use this prompt when the agent has a clear natural language question about the codebase but lacks the specific function names, file paths, or literal strings needed for an effective search. It is appropriate for initial codebase exploration, bug investigation, feature location, and dependency tracing. The prompt requires the agent's current working directory, available search tools, and the codebase's primary language or framework as context. It should not be used when the agent already knows the exact file and line number, when the task is a simple file read rather than a search, or when the search tool has a strict regex engine that cannot handle the generated alternatives.
Avoid this prompt for real-time, latency-sensitive search loops where the overhead of an LLM call is unacceptable; a cached or heuristic-based query expander is a better fit. It is also unsuitable for searching binary files, generated code, or vendored dependencies unless those directories are explicitly included in the search scope. For high-risk codebases where a missed result could cause a security or compliance incident, always pair this prompt with a post-search validation step that confirms the critical code was found, and escalate to a human operator if the search yields zero results for a safety-sensitive query.
Use Case Fit
Where this prompt works and where it does not. Use these cards to decide if semantic search query generation is the right tool for your codebase exploration workflow.
Good Fit: Natural Language to Structured Search
Use when: a developer or agent expresses intent in natural language ("find where authentication logic checks session expiry") and needs a structured query for grep, ripgrep, or AST tools. Guardrail: always validate the generated query against a known set of expected results for a calibration query before trusting it on novel inputs.
Bad Fit: Exact Symbol Lookup
Avoid when: the task requires finding a specific function definition, class declaration, or type signature that a language server or compiler index can resolve deterministically. Guardrail: route exact symbol lookups to LSP-based tools and reserve semantic query generation for fuzzy, intent-driven searches where no single symbol name captures the goal.
Required Inputs: Codebase Context and Intent Signal
Risk: generating queries without understanding the repository's language, framework conventions, or file naming patterns produces patterns that match nothing or everything. Guardrail: always provide the prompt with a repository summary, language/framework hints, and example file paths before asking for query generation. Include a negative example of what should not match.
Operational Risk: Context Window Flooding
Risk: overly broad generated patterns (e.g., searching for session across an entire monorepo) return thousands of results and exhaust the agent's context window. Guardrail: implement a result-count cap in the harness. If a generated query returns more than a threshold (e.g., 200 matches), automatically request a narrower query with additional constraints before presenting results to the agent.
Operational Risk: Silent Misses from Over-Specificity
Risk: the prompt generates a pattern that is too specific (e.g., an exact string match for a log message that appears with slight variations) and silently returns zero results, leading the agent to conclude code doesn't exist. Guardrail: always pair semantic query generation with a recall check—run a broader fallback query and diff the results. Flag zero-result queries for human or agent review before accepting the negative finding.
When to Escalate: Cross-Cutting Concerns
Risk: the intent spans multiple architectural layers (e.g., "find all places where user input reaches the database") and no single query pattern can capture the full data flow. Guardrail: detect multi-hop intent and decompose into a chain of queries with intermediate results feeding the next step. If decomposition fails, escalate to a human to provide a manual trace or architecture diagram.
Copy-Ready Prompt Template
A reusable prompt template for translating natural language intent into structured code search queries, ready to be copied and adapted for your agent's search tool harness.
This prompt template is designed to be the core instruction set for an AI coding agent that must convert a developer's natural language question into a precise, structured search query. The template uses square-bracket placeholders for all dynamic inputs, allowing you to wire it directly into an application harness. The goal is to produce queries that are specific enough to avoid flooding the context window with irrelevant results, yet flexible enough to catch semantically related code that a literal grep would miss.
textYou are a code search query generator. Your task is to translate a natural language intent into a set of structured search queries for a codebase exploration tool. ## Input - **Intent:** [USER_INTENT] - **Codebase Context:** [CODEBASE_CONTEXT] - **Available Search Tools:** [AVAILABLE_SEARCH_TOOLS] - **Output Schema:** [OUTPUT_SCHEMA] ## Instructions 1. Analyze the user's intent to identify the core code entities, relationships, or patterns they are looking for. 2. Generate a primary search query using the most appropriate tool (e.g., `ripgrep` for patterns, `ast-grep` for structural searches). 3. Generate 2-3 alternative queries that use different patterns, synonyms, or tool types to maximize recall. For example, if searching for "error handling in the auth module," generate one query for `try/catch` blocks, another for `auth.*error` function calls, and a third for `throw new.*AuthError`. 4. For each query, assign a relevance score (1-10) based on how directly it addresses the user's intent. 5. If the intent is ambiguous, generate queries for the top 2 most likely interpretations and flag the ambiguity. ## Constraints - [CONSTRAINTS] - Do not generate queries that would match more than 500 files unless explicitly requested for a broad scan. - Prefer queries that target specific directories or file types when the codebase context provides them. - Exclude common vendor, test fixture, and generated code paths unless the intent suggests otherwise. ## Examples [EXAMPLES] ## Output Format Return a valid JSON object conforming to the provided Output Schema.
To adapt this template, start by defining your [OUTPUT_SCHEMA] to enforce a strict structure, such as a JSON object with an array of query objects, each containing query_string, tool_type, target_paths, and relevance_score fields. The [CONSTRAINTS] placeholder should be replaced with project-specific rules, like excluding certain directories or enforcing a maximum file match count. The [EXAMPLES] placeholder is critical for few-shot learning; provide at least two examples that demonstrate how a vague intent maps to a set of precise, alternative queries. After generating the queries, your application harness should validate the JSON structure, check that the tool_type is in the [AVAILABLE_SEARCH_TOOLS] list, and log any queries that exceed your file-match threshold for human review before execution.
Prompt Variables
Inputs the semantic search query generation prompt needs to produce reliable, executable code search queries. Each variable must be validated before the prompt is called to prevent overly broad or overly specific pattern generation.
| Placeholder | Purpose | Example | Validation Notes |
|---|---|---|---|
[USER_INTENT] | Natural language description of what the developer wants to find in the codebase | Find where authentication middleware checks JWT expiry | Must be non-empty string with at least one actionable verb. Reject if intent is purely conversational or meta-level (e.g., 'how do I write a search query') |
[LANGUAGE] | Target programming language to scope search patterns and syntax conventions | TypeScript | Must match a known language identifier from the repository's detected languages. Null allowed if multi-language search is intended, but requires explicit flag |
[SEARCH_TOOL] | The specific search tool the generated query targets, which determines pattern syntax | ripgrep | Must be one of: ripgrep, grep, ast-grep, tree-sitter, or codeql. Reject unknown tools. Tool choice determines regex flavor and flag support |
[REPOSITORY_CONTEXT] | Brief structural summary of the codebase to ground query generation in actual conventions | NestJS monorepo with modules under apps/ and shared libs under libs/ | Must contain at least directory structure hints and framework name. Validate that context is derived from actual repository scan, not hallucinated. Null allowed for first-pass exploration |
[SCOPE_PATH] | File or directory path to restrict search scope, preventing results from irrelevant areas | apps/api/src/auth/ | Must be a valid relative path within the repository. Validate path exists in repo tree. Null allowed for repository-wide search but must be explicit |
[RESULT_COUNT_TARGET] | Desired number of results to guide pattern specificity tuning | 10-20 | Must be an integer range or single integer between 1 and 200. Reject values over 200 to prevent context window flooding. Default to 20 if not specified |
[PREVIOUS_QUERY_FEEDBACK] | Feedback from a prior search attempt to refine the next query iteration | Previous pattern 'jwt.*expir' returned 200+ results, too broad. Need to narrow to middleware-specific files. | Must be null on first attempt. On retry, must contain a specific failure reason and result count. Reject vague feedback like 'didn't work' |
Implementation Harness Notes
How to wire the semantic search query generation prompt into a codebase exploration agent or developer tool.
This prompt is designed to sit between a natural language interface and a code search backend such as ripgrep, ast-grep, or a language server's symbol search. The agent receives a developer question like "where is authentication logic implemented?" and must produce structured queries that the search tool can execute directly. The prompt is not a standalone chatbot response; it is a query-generation step in a retrieval pipeline. The output should be a JSON array of query objects, each containing a pattern, optional file type filter, and a relevance score, so the harness can iterate through queries in priority order until sufficient results are found or the query budget is exhausted.
Wire this prompt into an agent loop with a configurable max_queries parameter (default 5) and a min_results threshold (default 3). After each query executes, count the results. If results exceed a context-window flood threshold (e.g., 200 matches), append a narrowing constraint to the next query generation call: [PREVIOUS_QUERY] returned too many results. Generate a more specific pattern. If results are zero, append: [PREVIOUS_QUERY] returned no results. Try alternative patterns, synonyms, or broader file scopes. The harness must track which queries have been tried to prevent infinite loops. Log every generated query, the result count, and whether it contributed to the final context bundle for observability and debugging.
For model choice, use a fast, instruction-tuned model such as GPT-4o-mini, Claude Haiku, or a local model like DeepSeek-Coder for latency-sensitive loops. This prompt rarely requires a frontier model because the task is structured pattern generation, not deep reasoning. Implement a timeout of 3 seconds per generation call and a circuit breaker that falls back to a static list of common patterns (e.g., the function name as a literal grep) if the model fails twice. Validate every generated query before execution: reject patterns with unbounded wildcards like .* alone, patterns shorter than 3 characters, or patterns that match the entire codebase (e.g., a single space). If the agent is operating in a regulated or high-risk codebase, log all generated queries for audit and require human approval before executing destructive or modifying operations—though search queries are read-only, the surrounding agent may not be.
The harness should maintain a session-level cache of query-to-result mappings to avoid re-running identical searches within the same task. When the agent assembles final context for the next reasoning step, include the query that found each result so downstream prompts can cite provenance. Avoid wiring this prompt directly to a user-facing chat without the search execution loop; raw query JSON confuses end users and invites manual copy-paste errors. Instead, expose the harness through a tool interface that the coding agent or IDE plugin calls programmatically.
Expected Output Contract
Defines the required JSON structure, field types, and validation rules for the semantic search query output. Use this contract to parse, validate, and route the generated queries to grep, ripgrep, or AST-based search tools.
| Field or Element | Type or Format | Required | Validation Rule |
|---|---|---|---|
query_intent | string | Must be a non-empty string summarizing the user's high-level goal. Validate length between 10 and 200 characters. | |
primary_patterns | array of strings | Must contain 1-5 valid regex or literal search strings. Each string must be non-empty and escape special characters if intended for literal search. Validate array length. | |
alternative_patterns | array of strings | If present, must contain 0-5 strings. Each string must be non-empty. Null or empty array is acceptable. Validate no duplicates with primary_patterns. | |
file_type_filters | array of strings | If present, must be an array of file extensions (e.g., '.py', '.ts'). Each string must start with a dot. Null allowed. Validate format with a regex check. | |
exclusion_patterns | array of strings | If present, must contain 0-5 regex strings to exclude false positives (e.g., 'test_', 'pycache'). Null allowed. Validate each string is a valid regex. | |
symbol_focus | string | If present, must be one of: 'function', 'class', 'interface', 'variable', 'import', 'comment', or null. Validate against the allowed enum list. | |
relevance_rationale | string | Must be a non-empty string explaining why the chosen patterns match the intent. Validate length between 20 and 500 characters. No structural validation beyond length. | |
confidence_score | number | Must be a float between 0.0 and 1.0 representing the model's confidence in the query's recall. Validate range. If below 0.6, trigger a retry or human review workflow. |
Common Failure Modes
Semantic search query generation fails in predictable ways. These cards cover the most common failure modes when translating natural language intent into codebase search queries, along with practical mitigations to keep your agent's search results relevant and bounded.
Overly Specific Patterns Miss Real Results
What to watch: The agent generates a single precise regex or AST pattern that matches the ideal case but misses real-world variants—different naming conventions, wrapper functions, or refactored implementations. Guardrail: Require the prompt to produce 3-5 pattern alternatives with explicit variant coverage (camelCase, snake_case, destructured imports, aliased references) and rank by expected recall.
Overly Broad Patterns Flood the Context Window
What to watch: The agent defaults to a broad keyword match like error or handle that returns thousands of results, overwhelming downstream context assembly and causing the agent to miss the relevant signal. Guardrail: Add a max_results constraint and require the prompt to include exclusion filters, file-type scoping, and directory boundaries before generating the query.
Natural Language Intent Is Ambiguous or Underspecified
What to watch: The user says "find the auth logic" but the codebase has OAuth handlers, session middleware, API key validation, and permission checks spread across 40 files. The agent picks one interpretation and misses the rest. Guardrail: Before generating search queries, require the prompt to produce a disambiguation step—list candidate interpretations, ask for clarification on scope, or generate queries for all plausible interpretations with labeled coverage.
Generated Queries Ignore the Repository's Actual Structure
What to watch: The agent generates queries assuming a flat file layout or standard framework conventions, but the target repo uses a non-standard directory structure, monorepo layout, or custom module resolution. Queries return nothing or garbage. Guardrail: Require the prompt to consume a repository map or directory inventory as input before generating queries, and validate that generated file paths match known directories.
Query Language Mismatch with Available Search Tools
What to watch: The agent generates an AST-aware query for tree-sitter, but the harness only has ripgrep available. Or it generates a ripgrep regex that would be trivial as a language-server symbol search. The query fails silently or returns wrong results. Guardrail: Include the available search tool capabilities and syntax constraints in the prompt context. Require the output to specify which tool each query targets and validate tool availability before execution.
No Relevance Ranking or Result Triage Plan
What to watch: The agent generates queries but doesn't specify how to rank or triage results. Downstream steps treat all matches equally, wasting context on boilerplate, test fixtures, or generated code that technically matches the pattern. Guardrail: Require the prompt output to include a ranking heuristic—prioritize files with recent commits, exclude generated directories, boost files in relevant module paths, and flag results that need human confirmation.
Evaluation Rubric
Criteria for evaluating the quality of generated semantic search queries before integrating them into a coding agent's retrieval pipeline. Each criterion targets a specific failure mode of the prompt.
| Criterion | Pass Standard | Failure Signal | Test Method |
|---|---|---|---|
Query Specificity | Generated query contains at least one concrete code token (function name, class, string literal) from the expected result set. | Query consists only of generic natural language with no code-specific terms, or uses only common English stop words. | Run prompt against 10 known code-search tasks. Manually verify each output contains a token present in the ground-truth target file. |
Pattern Alternative Coverage | For ambiguous intent, output includes 2-5 alternative patterns (regex or structured queries) covering different naming conventions (camelCase, snake_case). | Output provides a single monolithic regex with no alternatives, or alternatives are trivial character-case swaps. | Feed 5 ambiguous intents (e.g., 'find user auth'). Check output contains distinct patterns for 'auth', 'authenticate', 'login', 'signin'. |
Context Window Budget Adherence | Total characters across all generated patterns do not exceed 500 characters, preventing context flooding. | Output exceeds 500 characters or includes a full-file dump instead of targeted patterns. | Automated length check on output string. Flag any output > 500 chars as a failure. |
Negative Space Exclusion | Query includes explicit exclusion patterns (e.g., --glob '!test') to filter out test files, generated code, or vendor directories when intent implies application logic. | Query returns results dominated by test fixtures or node_modules when the user asked for application logic. | Run query against a benchmark repo. Assert that >80% of results originate from non-test, non-vendor directories. |
AST-Aware Structure | Output includes a structured query object with a 'type' field (e.g., 'function_call', 'class_def') when the intent targets a specific code construct. | Output is a flat string grep pattern when the user asked for 'all classes that inherit from BaseHandler'. | Schema validation: parse output as JSON. Check for presence of 'type' key when input contains class/inheritance language. |
Relevance Ranking Hints | Output includes a 'priority' or 'weight' field for each pattern, with the most likely match ranked first. | All patterns have identical priority or are returned in a random order, causing the agent to waste cycles on low-probability matches. | Check output JSON for a 'priority' field. Verify the first pattern is the most specific (longest, most code-like) pattern. |
Hallucination Resistance | Generated patterns contain only tokens and conventions plausible for the described tech stack; no invented API names. | Query includes a function name that does not exist in the target language's standard library or the specific framework. | Cross-reference generated tokens against a whitelist of the repo's actual dependencies. Flag unknown tokens for manual review. |
Enabling Efficiency, Speed & Accuracy
Intelligent Analysis, Decision & Execution
We build AI systems for teams that need search across company data, workflow automation across tools, or AI features inside products and internal software.
Talk to Us
Search across company data
Give teams answers from docs, tickets, runbooks, and product data with sources and permissions.
Useful when people spend too long searching or get different answers from different systems.

Automate internal workflows
Use AI to route work, draft outputs, trigger actions, and keep approvals and logs in place.
Useful when repetitive work moves across multiple tools and teams.

Add AI to products and internal tools
Build assistants, guided actions, or decision support into the software your team or customers already use.
Useful when AI needs to be part of the product, not a separate tool.
Adapt This Prompt
How to adapt
Use the base prompt with a single model call and minimal post-processing. Drop the [OUTPUT_SCHEMA] constraint and accept free-text query suggestions. Replace structured ranking with a simple ordered list.
codeGenerate search queries for: [NATURAL_LANGUAGE_INTENT] Codebase language: [LANGUAGE] Return a list of grep-compatible patterns.
Watch for
- Overly specific regex that matches nothing
- Missing pattern alternatives when the first query fails
- No relevance ordering, flooding the context window with noise

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.
Partnered with leading AI, data, and software stack.
How We Work
Custom AI workflows for your Business
One-fit-all AI don't work for modern businesses. At Inferensys, we aim to understand your business & custom requirements; which we use to define most efficient agentic workflows, the data, and the tools for your business.
01
Review the use case
We understand the task, the users, and where AI can actually help.
Read more02
Pick the right approach
We define what needs search, automation, or product integration.
Read more03
Build the first useful version
We implement the part that proves the value first.
Read more04
Improve from there
We add the checks and visibility needed to keep it useful.
Read moreThe first call is a practical review of your use case and the right next step.
Talk to Us