Skip to content
tnsaiDocs
GitHub

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.

StrategyAdds instructions asking the model toMulti-passPost-processing
CHAIN_OF_THOUGHTReason step by step before the final answerNoNo
CHAIN_OF_VERIFICATIONAnswer, write verification questions, answer them, then reviseYesYes
CONFIDENCE_WEIGHTEDGive a confidence level from 0 to 100%, its assumptions, and alternatives below 70%NoNo
STRUCTURED_THINKINGWork through UNDERSTAND, ANALYZE, STRATEGIZE and EXECUTENoNo
MULTI_PERSPECTIVEWeigh technical, business, user-experience and risk views, then recommendNoNo
CONSTRAINT_FIRSTSeparate hard constraints from soft preferences before answeringNoNo
ITERATIVE_REFINEMENTDraft, critique, refine and reviewYesYes
CONTEXT_BOUNDARIESSeparate context, focus, task and constraints, and say when information is missingNoNo
FEW_SHOT_EXAMPLESFollow the good and bad examplesNoNo
META_PROMPTINGDesign the best prompt for the task, then answer itYesNo
SIX_PART_ANATOMYAnswer in six parts: role, objective, request, process, output, stopNoNo
ATOM_OF_THOUGHTSplit the problem into independent sub-problems, solve each, then combineYesNo

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).

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.

MethodAdds 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.

ValueInstruction
TEXTProvide your response as plain text.
JSONProvide your response as valid JSON.
MARKDOWNFormat your response using Markdown.
MARKDOWN_TABLEFormat your response as a Markdown table.
BULLET_POINTSUse bullet points for your response.
NUMBERED_LISTUse a numbered list for your response.
STRUCTUREDUse clear sections with headers for your response.
CODEProvide code with comments explaining each section.
COMPARISON_TABLECreate a comparison table with pros/cons.

EnhancedPrompt

MethodReturns
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.

MethodReturns
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.