> ## Documentation Index
> Fetch the complete documentation index at: https://docs.praison.ai/llms.txt
> Use this file to discover all available pages before exploring further.

# Query Rewrite

> Optimize queries for better RAG retrieval using QueryRewriterAgent

The `--query-rewrite` flag transforms user queries to improve RAG retrieval quality using the QueryRewriterAgent.

## Quick Start

```bash theme={"theme":{"light":"vitesse-light","dark":"vitesse-dark"}}
praisonai "AI trends" --query-rewrite
```

<img src="https://mintcdn.com/praisonai/fT4nF3hY6KPMOPvS/docs/cli/query-rewrite-query-rewrite.gif?s=c73c84d5e3c787629ada8c50dc8e1f1f" alt="Query Rewrite Demo" width="1497" height="1104" data-path="docs/cli/query-rewrite-query-rewrite.gif" />

## Usage

### Basic Query Rewrite

```bash theme={"theme":{"light":"vitesse-light","dark":"vitesse-dark"}}
praisonai "AI trends" --query-rewrite
```

**Expected Output:**

```
🔄 Query rewritten: "What are the current trends in Artificial Intelligence?"

╭─ Agent Info ─────────────────────────────────────────────────────────────────╮
│  👤 Agent: DirectAgent                                                       │
│  Role: Assistant                                                             │
╰──────────────────────────────────────────────────────────────────────────────╯

╭────────────────────────────────── Response ──────────────────────────────────╮
│ Current AI trends include...                                                 │
╰──────────────────────────────────────────────────────────────────────────────╯
```

### With Search Tools

```bash theme={"theme":{"light":"vitesse-light","dark":"vitesse-dark"}}
# Rewrite with search tools (agent decides when to search)
praisonai "latest developments" --query-rewrite --rewrite-tools "internet_search"

# Works with any prompt
praisonai "explain quantum computing" --query-rewrite -v
```

### Combine with Other Flags

```bash theme={"theme":{"light":"vitesse-light","dark":"vitesse-dark"}}
# Query rewrite with prompt expansion
praisonai "AI news" --query-rewrite --expand-prompt

# Query rewrite with deep research
praisonai research --query-rewrite "AI trends"

# Query rewrite with verbose output
praisonai "explain quantum computing" --query-rewrite -v
```

## How It Works

1. **Query Analysis**: The QueryRewriterAgent analyzes your input
2. **Strategy Selection**: Automatically selects the best rewrite strategy
3. **Query Transformation**: Expands abbreviations, adds context, fixes typos
4. **Execution**: The rewritten query is used for the task

```mermaid theme={"theme":{"light":"vitesse-light","dark":"vitesse-dark"}}
flowchart LR
    A[Original Query] --> B[QueryRewriterAgent]
    B --> C{Strategy}
    C -->|BASIC| D[Expand & Clarify]
    C -->|HYDE| E[Hypothetical Doc]
    C -->|STEP_BACK| F[Broader Context]
    C -->|SUB_QUERIES| G[Decompose]
    D --> H[Rewritten Query]
    E --> H
    F --> H
    G --> H
    H --> I[Execute Task]
```

## Rewrite Strategies

| Strategy     | Description                                          | Best For                   |
| ------------ | ---------------------------------------------------- | -------------------------- |
| BASIC        | Expand abbreviations, fix typos, add context         | General queries            |
| HYDE         | Generate hypothetical document for semantic matching | Conceptual questions       |
| STEP\_BACK   | Generate higher-level concept questions              | Specific technical queries |
| SUB\_QUERIES | Decompose multi-part questions                       | Complex queries            |
| MULTI\_QUERY | Generate multiple paraphrased versions               | Ambiguous queries          |
| CONTEXTUAL   | Resolve references using conversation history        | Follow-up questions        |
| AUTO         | Automatically detect best strategy                   | Default                    |

## Examples

### Technical Query

```bash theme={"theme":{"light":"vitesse-light","dark":"vitesse-dark"}}
praisonai "GPT-4 vs Claude 3?" --query-rewrite
```

**Rewritten to:** "What are the key differences between OpenAI's GPT-4 and Anthropic's Claude 3 language models in terms of capabilities, performance, and use cases?"

### Ambiguous Query

```bash theme={"theme":{"light":"vitesse-light","dark":"vitesse-dark"}}
praisonai "RAG setup" --query-rewrite
```

**Rewritten to:** "How do I set up a Retrieval-Augmented Generation (RAG) system, including document ingestion, embedding generation, vector storage, and query processing?"

### Follow-up Query

```bash theme={"theme":{"light":"vitesse-light","dark":"vitesse-dark"}}
praisonai "What about cost?" --query-rewrite
```

**Rewritten to:** "What are the cost considerations and pricing models for implementing this solution?"

## Programmatic Usage

```python theme={"theme":{"light":"vitesse-light","dark":"vitesse-dark"}}
from praisonaiagents import QueryRewriterAgent, RewriteStrategy

agent = QueryRewriterAgent(model="gpt-4o-mini")

# Basic rewrite
result = agent.rewrite("AI trends")
print(result.primary_query)  # "What are the current trends in Artificial Intelligence?"

# With specific strategy
result = agent.rewrite("What is quantum computing?", strategy=RewriteStrategy.HYDE)

# Step-back for broader context
result = agent.rewrite("GPT-4 vs Claude 3?", strategy=RewriteStrategy.STEP_BACK)

# Sub-queries for complex questions
result = agent.rewrite("RAG setup and best embedding models?", strategy=RewriteStrategy.SUB_QUERIES)

# Contextual with chat history
result = agent.rewrite("What about cost?", chat_history=[...])
```

## Best Practices

<Tip>
  Use `--query-rewrite` for RAG and search optimization. For expanding task prompts, use `--expand-prompt` instead.
</Tip>

<Warning>
  Query rewriting adds an additional LLM call. Use `--metrics` to monitor token usage.
</Warning>

| Use Case                | Flag                              |
| ----------------------- | --------------------------------- |
| RAG/Search optimization | `--query-rewrite`                 |
| Task prompt expansion   | `--expand-prompt`                 |
| Both                    | `--query-rewrite --expand-prompt` |

## Related

* [Query Rewriter Agent](/agents/query-rewriter)
* [Prompt Expansion CLI](/cli/prompt-expansion)
* [Deep Research CLI](/cli/deep-research)
