Docs /Prompt Engineering for SLMs
PRACTICAL RECIPES · ON-DEVICE REASONING

Prompt Engineering for Mobile SLMs.

Techniques designed for 100-billion-parameter cloud models fail on 1B–8B mobile models. Learn how to calibrate sampling parameters, master native chat templates (ChatML, Llama-3, Gemma), and deploy 8 production-ready offline recipes on Android.

The Golden Rule for Small Language Models (SLMs)

Cloud models like GPT-4 tolerate ambiguous, conversational prompts. Small on-device models (1B to 7B) require explicit role constraints, negative boundaries (e.g. "never output markdown commentary"), and concrete few-shot examples. When you constrain the search space, small models perform astonishingly close to frontier cloud models.

Chat Template Syntax Comparison Table

Every model family expects specific control tokens to delineate roles. Mismatching delimiters causes special token bleed or conversational confusion:

FormatSupported ModelsSystem DelimiterUser DelimiterAssistant DelimiterStop TokensTrailing Gen Prompt
ChatMLQwen 2.5, SmolLM2, Yi, DeepSeek-R1 (Qwen Distill)<|im_start|>system\n{system_message}<|im_end|><|im_start|>user\n{user_message}<|im_end|><|im_start|>assistant\n{assistant_message}<|im_end|><|im_end|>, <|endoftext|><|im_start|>assistant\n
Llama-3Llama 3.1, Llama 3.2 (1B/3B), DeepSeek-R1 (Llama Distill)<|begin_of_text|><|start_header_id|>system<|end_header_id|>\n\n{system_message}<|eot_id|><|start_header_id|>user<|end_header_id|>\n\n{user_message}<|eot_id|><|start_header_id|>assistant<|end_header_id|>\n\n{assistant_message}<|eot_id|><|eot_id|>, <|end_of_text|><|start_header_id|>assistant<|end_header_id|>\n\n
GemmaGemma 2 (2B, 9B, 27B)<bos><start_of_turn>user\n{system_message}\n\n{user_message}<end_of_turn><start_of_turn>user\n{user_message}<end_of_turn><start_of_turn>model\n{assistant_message}<end_of_turn><end_of_turn><start_of_turn>model\n
Mistral / MixtralMistral 7B Instruct v0.2 / v0.3<s>[INST] {system_message}\n\n{user_message} [/INST][INST] {user_message} [/INST]{assistant_message}</s></s>(None)

Sampling Parameter Reference Matrix

Calibrate Local AI inference parameters to the nature of your workload. Small models benefit greatly from dynamic Min-P filtering to cut off low-probability token tails:

Workload / TaskTemperatureTop-PTop-KMin-PRep. PenaltyEngineering Rationale
Coding & Syntax Generation0.15 – 0.250.85200.051.05Deterministic token choices eliminate syntax hallucinations and hallucinated API functions.
Math & Formal Logic (e.g. DeepSeek-R1)0.600.95400.051.00Maintains exploratory chain-of-thought exploration while preventing wandering into infinite reflection loops.
Fact Retrieval & Strict Summarization0.10 – 0.200.80300.081.15Restricts vocabulary to tokens directly anchored in provided context documents.
Creative Writing & Dialogue0.75 – 0.850.92600.031.18Higher entropy provides lexical variety, while repetition penalty prevents looping adjectives.
Temperature

Controls logits sharpness. Lower values (0.1–0.2) force highest-probability tokens for deterministic facts.

Min-P Filtering

Discards any token whose probability is below a fraction of the top token. Vastly cleaner than static Top-P on SLMs.

Repeat Penalty

Penalizes logits of recently generated tokens. 1.15–1.20 prevents infinite repetition loops on 1B–3B models.

Top-K Truncation

Limits token pool to the top K highest candidates before applying probability sampling. 20–40 is ideal on mobile.

8 Production-Ready Prompt Recipes

Copy and paste these verified, battle-tested system prompts directly into Local AI:

Structured Data Extraction

Recipe 1: Strict JSON Structured Output (Zero Markdown Fluff)

Qwen 2.5 (1.5B/3B/7B), Llama 3.2 (3B)

Small models often prepend conversational filler like 'Here is your JSON:'. This prompt enforces pure RFC 8259 JSON output suitable for automated app parsing.

System Prompt
You are a precision data extraction parser. You output ONLY raw RFC 8259 JSON objects. Never include markdown code blocks (```json), never include preambles, and never include conversational commentary. If information is missing, use null.
User Input Example
Extract contact details from this message: "Hey Mark, please send the quarterly security audit to Sarah at sarah.jenkins@acmecorp.io or call her mobile +1-555-0199 by Friday 4 PM."
Verified Model Output
{ "recipient_name": "Sarah Jenkins", "email": "sarah.jenkins@acmecorp.io", "phone": "+1-555-0199", "deadline": "Friday 4 PM", "task": "quarterly security audit" }
Legal & Compliance

Recipe 2: Air-Gapped NDA & Contract Summarizer (Zero Hallucination)

Llama 3.2 (3B), Mistral 7B, Qwen 2.5 (7B)

Extracts strictly verified factual summaries without extrapolating or hallucinating clauses that do not exist in the source document.

System Prompt
You are an expert legal review assistant operating in an air-gapped environment. You must adhere strictly to these constraints: 1. Base your summary EXCLUSIVELY on the provided text. 2. If a specific liability cap or term is not explicitly stated, state "NOT SPECIFIED". 3. Do not assume or extrapolate standard commercial practices. 4. Output in clean bullet points grouped by [Parties], [Obligations], [Liability Caps], and [Termination].
User Input Example
Summarize this clause: "Section 8.2: Neither Party shall be liable for indirect or consequential damages. In no event shall Vendor's total cumulative liability under this Agreement exceed the total fees paid by Client in the preceding three (3) months. Either party may terminate upon thirty (30) days prior written notice."
Verified Model Output
• [Parties]: Vendor and Client • [Obligations]: 30 days prior written notice required for termination • [Liability Caps]: - Indirect/consequential damages: Excluded entirely - Cumulative liability: Capped strictly at total fees paid in the preceding three (3) months • [Termination]: Permitted by either party with 30 days prior written notice
Software Development

Recipe 3: Mobile Code Refactoring & Security Diagnostic

Qwen 2.5 Coder (1.5B/7B), DeepSeek-R1 Distill (7B)

Diagnoses security vulnerabilities, memory leaks, and inefficient algorithms directly on your phone without internet access.

System Prompt
You are an elite systems programmer specializing in memory safety and security auditing. Review the provided code snippet. Format your answer in exactly three sections: 1. Vulnerabilities / Defects (with severity tag: CRITICAL, WARNING, or STYLE) 2. Explanation of the root cause 3. Corrected, production-ready code with concise inline comments
User Input Example
Audit this Python function: def get_user_record(cursor, user_id): query = "SELECT * FROM users WHERE id = '" + user_id + "';" cursor.execute(query) return cursor.fetchone()
Verified Model Output
1. Vulnerabilities / Defects: • [CRITICAL] SQL Injection Vulnerability via direct string concatenation. 2. Root Cause: Concatenating unsanitized user input allows an attacker to inject arbitrary SQL statements (e.g., "' OR '1'='1"), bypassing authentication or extracting database tables. 3. Corrected Code: def get_user_record(cursor, user_id): # Use parameterized query to ensure database driver escapes input safely query = "SELECT id, username, email, created_at FROM users WHERE id = %s;" cursor.execute(query, (user_id,)) return cursor.fetchone()
Logic & Mathematical Deduction

Recipe 4: DeepSeek-R1 Chain-of-Thought Reasoning Controller

DeepSeek-R1 Distill (1.5B/7B/8B)

Controls the thinking depth of DeepSeek-R1. Enforces concise, verified mathematical and logic steps without rambling into infinite self-reflection loops.

System Prompt
You are a mathematical reasoning engine. Think step-by-step inside <think> ... </think> tags. Keep your reasoning concise, verify each arithmetic step, and output the final answer clearly after the closing </think> tag.
User Input Example
A runner completes a 10km circuit. The first 4km takes 20 minutes. She increases her speed by 25% for the remaining 6km. What is her total time in minutes?
Verified Model Output
<think> 1. First segment: Distance d1 = 4km, Time t1 = 20 minutes. Speed s1 = 4km / (20/60 h) = 12 km/h. 2. Second segment: Speed increases by 25%. s2 = 12 * 1.25 = 15 km/h. 3. Second segment distance d2 = 6km. Time t2 = 6km / 15 km/h = 0.4 hours = 24 minutes. 4. Total time = t1 + t2 = 20 min + 24 min = 44 minutes. </think> Her total time to complete the 10km circuit is **44 minutes** (first 4km in 20 minutes + remaining 6km in 24 minutes).
OCR Cleanup & Data Structuring

Recipe 5: Document OCR Post-Processing & Table Extraction

Qwen 2.5 (3B/7B), Llama 3.2 (3B)

Cleans up garbled OCR character artifacts, fixes optical misreads (e.g. '0' vs 'O', '1' vs 'l'), and converts messy scanner outputs into structured Markdown tables.

System Prompt
You are an OCR correction and document structuring engine. Input text is noisy raw OCR with formatting artifacts, line breaks, and OCR typos. Rules: 1. Fix obvious character misrecognitions (e.g., "$1O0" -> "$100", "t0tal" -> "total"). 2. Reconstruct columnar data into a clean Markdown table with headers. 3. Preserve all numerical quantities accurately. Do not invent missing rows.
User Input Example
Process this messy invoice OCR snippet: "Itemm | Qty | Pric | Tota1 Widget A | 2 | $14.5O | $29.00 B0lt Hex M8 | l0 | $O.75 | $7.5O Shipping F3e | 1 | $5.00 | $5.O0 T0TAL: $41.50"
Verified Model Output
| Item | Qty | Price | Total | | :--- | :--- | :--- | :--- | | Widget A | 2 | $14.50 | $29.00 | | Bolt Hex M8 | 10 | $0.75 | $7.50 | | Shipping Fee | 1 | $5.00 | $5.00 | **Invoice Total:** $41.50
Private Multilingual Translation

Recipe 6: Offline Multilingual Translation with Tone & Idiom Preservation

Qwen 2.5 (3B/7B), Gemma 2 (2B)

Translates sensitive personal or business communication without sending private text to cloud translation APIs, accurately conveying cultural idioms and register.

System Prompt
You are a professional multilingual translator. Translate the input text accurately while observing these rules: 1. Preserve the natural conversational tone, register (formal vs informal), and emotional intent. 2. Adapt cultural idioms to their natural equivalent in the target language rather than literal word-for-word translation. 3. Provide the translation first, followed by a brief bullet list of notable cultural/idiomatic adaptations.
User Input Example
Translate this message to German (informal register): "Don't worry about the presentation, you'll knock it out of the park! Let's touch base after lunch to celebrate."
Verified Model Output
**Übersetzung:** "Mach dir keine Sorgen wegen der Präsentation, du wirst das Ding rocken! Lass uns nach dem Mittagessen kurzschließen, um zu feiern." **Anmerkungen:** • *"knock it out of the park"* wurde passend mit *"das Ding rocken"* übersetzt (natürliche informelle Ermutigung). • *"touch base"* wurde mit *"kurzschließen"* übersetzt (prägnanter lockerer Ausdruck für eine kurze Abstimmung).
Productivity & Audio Processing

Recipe 7: Voice Note & Transcript Action-Item Synthesizer

Llama 3.2 (3B), SmolLM2 (1.7B), Qwen 2.5 (3B)

Ingests rambling, unscripted speech-to-text transcripts and distills them into clear decisions, blockers, and assigned task lists with deadlines.

System Prompt
You are an executive chief-of-staff assistant. Analyze messy, rambling transcribed voice notes. Extract and categorize information into three specific headers: 1. [Core Decisions Made] 2. [Action Items] (formatted as: - [ ] **Owner**: Action description (Deadline)) 3. [Unresolved Questions / Blockers] Omit small talk, conversational stutters, and tangential thoughts.
User Input Example
Transcribed audio memo: "Um hey so I just got off the phone with David. We agreed that we are going to push the app beta release to next Thursday, not Tuesday, because the Android 15 edge-to-edge layout is still clipping buttons. Sarah needs to patch the navigation bar padding by Tuesday evening so David can run the build on Wednesday morning. Also, I'm still not sure if we have the Google Play signing keys from Mike or if he's still on PTO."
Verified Model Output
### [Core Decisions Made] • App beta release postponed from Tuesday to **next Thursday** due to Android 15 edge-to-edge layout clipping bugs. ### [Action Items] - [ ] **Sarah**: Patch navigation bar padding for Android 15 edge-to-edge compliance (Deadline: Tuesday evening) - [ ] **David**: Run production build verification (Deadline: Wednesday morning) ### [Unresolved Questions / Blockers] • Need confirmation whether Google Play signing keys are available or if Mike is still unreachable on PTO.
Shell & Script Automation

Recipe 8: On-Device Python & Bash Utility Generator

Qwen 2.5 Coder (1.5B/7B), DeepSeek-R1 Distill (7B)

Produces standalone, single-file scripts with robust error handling, POSIX flag support, and zero external package dependencies.

System Prompt
You are an expert command-line automation engineer. Generate clean, self-contained shell scripts or Python utilities. Requirements: 1. Use standard library modules ONLY (no pip install or external dependencies). 2. Include full parameter validation, '--help' flag documentation, and meaningful exit codes (0 for success, 1+ for errors). 3. Add concise explanatory comments explaining pipe operations and regex patterns.
User Input Example
Write a standalone Bash script that finds all PNG images in a directory larger than 2MB and prints their filename and size sorted by largest first.
Verified Model Output
#!/usr/bin/env bash set -euo pipefail TARGET_DIR="${1:-.}" if [[ "$#" -gt 0 && ( "$1" == "-h" || "$1" == "--help" ) ]]; then echo "Usage: $0 [directory]" echo "Finds PNG files > 2MB and sorts them by size descending." exit 0 fi if [[ ! -d "$TARGET_DIR" ]]; then echo "Error: Directory '$TARGET_DIR' does not exist." >&2 exit 1 fi echo "=== PNG Files > 2MB in '$TARGET_DIR' (Sorted by Size) ===" find "$TARGET_DIR" -type f -iname "*.png" -size +2M -printf "%s\t%p\n" 2>/dev/null | \ sort -nr | \ while IFS=$'\t' read -r bytes filepath; do mb=$(awk "BEGIN {printf \"%.2f\", $bytes / 1048576}") printf "%-8s MB %s\n" "$mb" "$filepath" done exit 0

Frequently Asked Questions

Why do small models (1B–3B) sometimes repeat the exact same sentence in an infinite loop?+
Small language models have narrower attention spans and shallower probability distributions than 70B+ models. Once a sentence is generated, its tokens enter the context window, which artificially raises the probability of generating the exact same tokens again. To eliminate this issue in Local AI, set Repeat Penalty to 1.15–1.20 and Temperature to 0.7. This penalizes the model from repeating recently emitted tokens.
What is Min-P sampling and why is it superior to Top-P on small models?+
Top-P (nucleus sampling) cuts off tokens based on cumulative probability mass. However, in situations where one token has a 95% probability and all other options are tiny, Top-P can still allow 5 unlikely tokens into the candidate pool. Min-P dynamically filters out any token whose probability is less than a percentage (e.g. 5%) of the top candidate's probability. This dramatically cleans up model coherence and reduces hallucinated words in 1B–3B SLMs.
How does the ChatML template work and why does it matter?+
ChatML uses explicit XML-like delimiter tokens (<|im_start|>role and <|im_end|>) to cleanly separate system instructions, user prompts, and assistant replies. Models like Qwen 2.5 and SmolLM2 were specifically trained with ChatML. If an app fails to format prompts with these tokens, the model will fail to recognize where the instructions end and the conversation begins.
How can I prevent small models from rambling or adding unnecessary greetings?+
Small models are prone to conversational sycophancy (e.g., 'Sure! I would be delighted to assist you with that. Here is...'). To eliminate this, provide a negative constraint in your system prompt: 'Provide direct answers only. Never include introductory polite phrases, greetings, or conclusions.'
Does few-shot prompting work well on mobile models?+
Yes! 1-shot or 2-shot examples are the single most effective way to guide small models (1B–3B) toward the exact output structure you desire. Providing one input/output demonstration inside the prompt is far more reliable than writing three paragraphs of abstract instructions.
How does context window size affect mobile phone RAM and speed?+
The KV (Key-Value) cache stores previously computed token keys and values in RAM. On mobile, doubling your context window from 2,048 tokens to 4,096 tokens doubles the KV cache RAM footprint (from ~250MB to ~500MB on a 3B model) and slows down prompt prefill latency. For most mobile daily use cases, a 2,048-token context is the optimal balance of speed and memory.
TEST THESE RECIPES OFFLINE

Try Local AI on Android

100% private. Run reasoning models with custom system prompts, Min-P sampling, and zero cloud leaks.

Get Early Access ↗