# Prompt strategies

`PromptEnhancer` builds a system prompt from prompting techniques such as chain of thought or self-verification. It only writes text. You send the prompt to the model yourself, and `EnhancedResponse` reads the reply.

**Package:** `com.tnsai.prompt.strategy`

## Strategies

Each `PromptStrategy` adds an instruction to the system prompt. A multi-pass strategy asks the model to work in several passes inside one reply; the framework makes one call, not several.

| Strategy | Adds instructions asking the model to | Multi-pass | Post-processing |
|---|---|:-:|:-:|
| `CHAIN_OF_THOUGHT` | Reason step by step before the final answer | No | No |
| `CHAIN_OF_VERIFICATION` | Answer, write verification questions, answer them, then revise | Yes | Yes |
| `CONFIDENCE_WEIGHTED` | Give a confidence level from 0 to 100%, its assumptions, and alternatives below 70% | No | No |
| `STRUCTURED_THINKING` | Work through UNDERSTAND, ANALYZE, STRATEGIZE and EXECUTE | No | No |
| `MULTI_PERSPECTIVE` | Weigh technical, business, user-experience and risk views, then recommend | No | No |
| `CONSTRAINT_FIRST` | Separate hard constraints from soft preferences before answering | No | No |
| `ITERATIVE_REFINEMENT` | Draft, critique, refine and review | Yes | Yes |
| `CONTEXT_BOUNDARIES` | Separate context, focus, task and constraints, and say when information is missing | No | No |
| `FEW_SHOT_EXAMPLES` | Follow the good and bad examples | No | No |
| `META_PROMPTING` | Design the best prompt for the task, then answer it | Yes | No |
| `SIX_PART_ANATOMY` | Answer in six parts: role, objective, request, process, output, stop | No | No |
| `ATOM_OF_THOUGHT` | Split the problem into independent sub-problems, solve each, then combine | Yes | No |

Each value has `getSystemInstruction()`, `getDescription()`, `isMultiPass()` and `requiresPostProcessing()`. The last two only describe the strategy; nothing in the framework acts on them.

## Build and send a prompt

`PromptEnhancer.builder()` collects strategies, a role, an objective, constraints, examples and an output format. `enhance(userMessage)` returns an `EnhancedPrompt`. For one strategy and nothing else, use `PromptEnhancer.withStrategy(strategy)`.

<!-- java-contract: src/main/java/com/example/tnsai/docs/PromptStrategiesBuilderExample.java -->
```java
package com.example.tnsai.docs;

import com.tnsai.llm.LLMClient;
import com.tnsai.prompt.strategy.EnhancedPrompt;
import com.tnsai.prompt.strategy.EnhancedResponse;
import com.tnsai.prompt.strategy.PromptEnhancer;
import com.tnsai.prompt.strategy.PromptStrategy;

public final class PromptStrategiesBuilderExample {
    private PromptStrategiesBuilderExample() {}

    static PromptEnhancer tutor() {
        return PromptEnhancer.builder()
            .role("Mathematics tutor")
            .objective("Solve algebra problems accurately")
            .strategy(PromptStrategy.CHAIN_OF_THOUGHT)
            .strategy(PromptStrategy.CONFIDENCE_WEIGHTED)
            .confidenceThreshold(0.7f)
            .constraint("Show all work")
            .positiveExample("2x = 10", "x = 5", "Divides both sides by 2")
            .negativeExample("2x = 10", "x = 10", "Forgets to divide")
            .outputFormat(PromptEnhancer.OutputFormat.STRUCTURED)
            .build();
    }

    // Build the prompt, send it yourself, then read the confidence line.
    static String solve(LLMClient llm, String problem) {
        EnhancedPrompt prompt = tutor().enhance(problem);
        String reply = llm.chat(prompt.getUserMessage(), prompt.getSystemPrompt()).getContent();

        EnhancedResponse parsed = EnhancedResponse.parse(reply);
        // getConfidence() is a percentage from 0 to 100.
        if (parsed.getConfidence().map(c -> c < 70f).orElse(false)) {
            return parsed.getMainContent() + "\nAlternatives: " + parsed.getAlternatives();
        }
        return parsed.getMainContent();
    }

    // For a model without a separate system prompt.
    static String combined(String problem) {
        return tutor().enhance(problem).getCombinedPrompt();
    }
}
```

## Builder methods

All methods return the builder and can be called in any order.

| Method | Adds to the system prompt |
|---|---|
| `strategy(PromptStrategy)` | The strategy's instruction. Call it once per strategy. |
| `role(String)` | The role line |
| `objective(String)` | The objective line |
| `constraint(String)`, `constraints(List<String>)` | A HARD CONSTRAINTS list |
| `softPreference(String)`, `softPreferences(List<String>)` | A SOFT PREFERENCES list |
| `processStep(String)`, `process(List<String>)` | A numbered PROCESS list |
| `positiveExample(input, output)`, `positiveExample(input, output, explanation)` | A good example |
| `negativeExample(input, badOutput, whyBad)` | A bad example |
| `outputFormat(PromptEnhancer.OutputFormat)` | The format instruction |
| `stopCondition(String)` | A STOP CONDITION line |
| `verificationQuestions(int)` | "Generate exactly N verification questions", with `CHAIN_OF_VERIFICATION` only |
| `refinementPasses(int)` | "Perform exactly N refinement passes", with `ITERATIVE_REFINEMENT` only |
| `confidenceThreshold(float)` | A threshold line as a percentage, with `CONFIDENCE_WEIGHTED` only. Pass a fraction: `0.7f` prints 70%. |

Examples are `PromptEnhancer.Example(input, output, explanation)` records; the two-argument constructor leaves the explanation `null`.

### `PromptEnhancer.OutputFormat`

This enum is nested in `PromptEnhancer`. It is not the `OutputFormat` used for parsing structured output.

| Value | Instruction |
|---|---|
| `TEXT` | Provide your response as plain text. |
| `JSON` | Provide your response as valid JSON. |
| `MARKDOWN` | Format your response using Markdown. |
| `MARKDOWN_TABLE` | Format your response as a Markdown table. |
| `BULLET_POINTS` | Use bullet points for your response. |
| `NUMBERED_LIST` | Use a numbered list for your response. |
| `STRUCTURED` | Use clear sections with headers for your response. |
| `CODE` | Provide code with comments explaining each section. |
| `COMPARISON_TABLE` | Create a comparison table with pros/cons. |

## `EnhancedPrompt`

| Method | Returns |
|---|---|
| `getSystemPrompt()` | The assembled system prompt |
| `getSystemPromptOptional()` | The same, as an `Optional<String>` |
| `getUserMessage()` | The message passed to `enhance` |
| `getCombinedPrompt()` | System prompt, a `---` separator, then the user message, for a model without a separate system prompt |
| `getStrategies()` | The strategies applied |
| `getOutputFormat()` | `Optional<PromptEnhancer.OutputFormat>` |
| `requiresMultiPass()`, `requiresPostProcessing()` | Whether any strategy is marked so |
| `expectsConfidenceScore()`, `expectsStructuredThinking()`, `expectsVerification()` | Whether `CONFIDENCE_WEIGHTED`, `STRUCTURED_THINKING` or `CHAIN_OF_VERIFICATION` is applied |
| `getEstimatedOverhead()` | The added characters divided by four, a rough token count |

## `EnhancedResponse`

`EnhancedResponse.parse(reply)` reads the sections the strategies asked for.

| Method | Returns |
|---|---|
| `getMainContent()` | The reply with the confidence, assumptions and alternatives lines removed |
| `getConfidence()` | `Optional<Float>`, a percentage from 0 to 100 |
| `isConfident(float)` | Whether the confidence is at least the threshold. The threshold is a percentage too: pass `70f`, not `0.7f`. |
| `getAssumptions()`, `getAlternatives()`, `getVerificationQuestions()` | The listed items |
| `getThinkingPhases()`, `getPhase(name)` | The `STRUCTURED_THINKING` phases |
| `hasStructuredThinking()`, `hasVerification()`, `hasAlternatives()` | Whether the sections are present |
| `getRawContent()` | The reply as received |

## `AgentBuilder` settings

`AgentBuilder.promptStrategy`, `promptStrategies` and `promptEnhancer` store their values, but nothing applies them. Not implemented: an agent's chat does not change. Call `enhance` yourself, as above.

## Related

- [Structured output](structured-output.md): typed replies.
- [LLM actions](actions.md#llm-actions): actions that call the model.
