惯性聚合 高效追踪和阅读你感兴趣的博客、新闻、科技资讯
阅读原文 在惯性聚合中打开

推荐订阅源

T
Threat Research - Cisco Blogs
博客园 - 聂微东
小众软件
小众软件
P
Proofpoint News Feed
Security Archives - TechRepublic
Security Archives - TechRepublic
OSCHINA 社区最新新闻
OSCHINA 社区最新新闻
TaoSecurity Blog
TaoSecurity Blog
博客园 - 司徒正美
罗磊的独立博客
N
News and Events Feed by Topic
cs.AI updates on arXiv.org
cs.AI updates on arXiv.org
S
Security Affairs
S
Security @ Cisco Blogs
freeCodeCamp Programming Tutorials: Python, JavaScript, Git & More
The GitHub Blog
The GitHub Blog
月光博客
月光博客
S
Secure Thoughts
P
Proofpoint News Feed
cs.CV updates on arXiv.org
cs.CV updates on arXiv.org
Forbes - Security
Forbes - Security
H
Heimdal Security Blog
W
WeLiveSecurity
K
KPMG report finds enterprise disconnect between AI and its ROI | CIO
L
LangChain Blog
T
The Blog of Author Tim Ferriss
NISL@THU
NISL@THU
Google DeepMind News
Google DeepMind News
Cloudbric
Cloudbric
H
Hacker News: Front Page
The Last Watchdog
The Last Watchdog
Hacker News - Newest:
Hacker News - Newest: "LLM"
C
Cisco Blogs
博客园 - 三生石上(FineUI控件)
博客园_首页
Exploit-DB.com RSS Feed
Exploit-DB.com RSS Feed
S
Schneier on Security
Project Zero
Project Zero
SecWiki News
SecWiki News
爱范儿
爱范儿
The Register - Security
The Register - Security
AI
AI
H
Hackread – Cybersecurity News, Data Breaches, AI and More
Y
Y Combinator Blog
L
Lohrmann on Cybersecurity
Application and Cybersecurity Blog
Application and Cybersecurity Blog
P
Privacy International News Feed
J
Java Code Geeks
S
Securelist
C
Cyber Attacks, Cyber Crime and Cyber Security
V
Visual Studio Blog

DEV Community

Authentication Security Deep Dive: From Brute Force to Salted Hashing (With Java Examples) Why AI Systems Don’t Fail — They Drift Spilling beans for how i learn for exam😁"Reinforcement Learning Cheat Sheet" I Replaced Chrome with Safari for AI Browser Automation. Here's What Broke (and What Finally Worked) How Python Borrows Other People's Work The $40 Architecture: Processing 1 Billion API Requests with 99.99% Uptime Vibe Coding: A Workflow Guide (From Zero to SaaS) Most webhook security guides protect the wrong side. The scary part is delivery. Headless CMS for TanStack Start: Build a Blog with Cosmic EU Age Verification App "Hacked in 2 Minutes" — What Actually Happened Comfy Cloud’s delete function does not actually remove files Running AI Models on GPU Cloud Servers: A Beginner Guide Event-driven media intelligence with AWS Step Functions and Bedrock I scored 500 AI prompts across 8 quality dimensions — here's what broke How to Call Google Gemini API from Next.js (Free Tier, No Backend Needed) The Portal Protocol: Reclaiming Human Connection in the Age of AI How to Fix Your Team's Scattered Knowledge Problem With a Self-Hosted Forum Intro to tc Cloud Functors: A Graph-First Mental Model for the Modern Cloud Designing Multi-Tenant Backends With Both Ownership and Team Access I Built a Neumorphic CSS Library with 77+ Components — Here's What I Learned PostgreSQL Performance Optimization: Why Connection Pooling Is Critical at Scale Cómo construí un SaaS multi-rubro para gestionar expensas en Argentina con FastAPI + Vue 3 🚀 I Built an Ethical Hacking Scanner Tool – Open Source Project I Replaced /usage and /context in Claude Code With a Single Statusline A Pythonic Way to Handle Emails (IMAP/SMTP) with Auto-Discovery and AI-Ready Design I Collected 8.9 Million Polymarket Price Points — Here's What I Found About How Markets Really Move EcoTrack AI — Carbon Footprint Tracker & Dashboard Everyone's Using AI. No One Agrees How. 5 self-hosted ebook managers worth trying in 2026 Building Your First AI Agent with LangChain: From Chatbot to Autonomous Assistant Common SOC 2 Failures (Real World) Stop Vibe-Checking Your AI App: A Practical Guide to Evals How to Use SonarQube and SonarScanner Locally to Level Up Your Code Quality Your Next To-Do App Is Dead — I Replaced Mine with an OpenClaw AI Sign a Nostr event in 60 lines of Python using coincurve — no nostr-sdk, no nbxplorer, no rust toolchain ITGC Audit Explained Like You’re in Big 4 Patch Tuesday abril 2026: Microsoft parcha 163 vulnerabilidades y un zero-day en SharePoint Stop scraping everything: a better way to track competitor price changes Listing on MCPize + the Official MCP Registry while routing payments OUTSIDE the marketplace — how I kept 100% of my x402 revenue Building an AI-Powered Risk Intelligence System Using Serverless Architecture Why We Ripped Function Overloading Out of Our AI Toolchain Testing AI-Generated Code: How to Actually Know If It Works SaaS Churn Is Killing Your Business. Here Is What to Do About It (Without a Support Team) The Speed of AI Is No Longer Linear - And Self-Improving Models Are Why How to Implement RBAC for MCP Tools: A Practical Guide for Engineering Teams From Standard Quote to Persuasive Proposal: AI Automation for Arborists I built a CLI that scaffolds complete multi-tenant SaaS apps Axios CVE-2025–62718: The Silent SSRF Bug That Could Be Hiding in Your Node.js App Right Now The dashboard that ended our friendship Data Pipelines Explained Simply (and How to Build Them with Python) The Hidden Cost of AI Systems Nobody Talks About. undefined vs undeclared, and how typeof behaves Switching from file-based jobs to NATS/Kafka in Rust without changing code io_uring Adventures: Rust Servers That Love Syscalls Why Agentic AI is Killing the Traditional Database The POUR principles of web accessibility for developers and designers Quantum Neural Network 3D — A Deep Dive into Interactive WebGL Visualization How To Install Caveman In Codex On macOS And Windows Automation Pipeline Reliability: Why Your Workflow Breaks When Nobody Is Watching I Built an 'Open World' AI Coding Agent — It Works From ANY Folder From Freelancing to Product: A Tech Service Company's SaaS Transformation China's AI Giants: Adding Tencent Hunyuan & ByteDance Doubao to AI University (74 Providers) On the Vibe Coders and Their Lies clerk: Auto-Summarize Your Claude Code Sessions AI Weekly — 2026/04/10–04/17 | The Model Lockdown Is Here, but the Toolchain Is the Real Battleground AI 週報 — 2026/04/10–2026/04/17 模型封鎖潮來了,但工具鏈才是真戰場 Maybe this is how Open-Source apps are born... 🚀 Fine-Tune LLMs with LoRA and QLoRA: 2026 Guide tRPC v11 + Next.js App Router: End-to-End Type Safety Without the Boilerplate ShadCN UI in 2026: Why I Stopped Installing Component Libraries and Started Owning My Components SaaS Billing in React Server Components: Stripe + Supabase Without a Single `useEffect` Join our DEV Weekend Challenge — $1,000 in Prizes Across TEN winners! Submissions Due April 20 at 6:59 AM UTC. Implementing FSRS Spaced Repetition in Flutter + Supabase — Adding Memory Science to an AI Learning App "I Texted My Localhost From the Train — Claude Code Fixed the Bug Before I Got Home" I Built a Sales Prep AI and It Went Deeper Than Expected Design to Code #2: One JSON, Eleven Outputs Solving the 100M-Row Problem: A Summary Table Pattern for High-Volume Push Notification Logs Flutter Web With Wasm: What Actually Changes For Developers I Built 50 Royalty-Free Soundtracks for My Side Project in a Weekend Using AI Music Generation The Vibe Coding Security Checklist: 7 Things to Check Before You Ship Stop Letting Googlebot Guess Fix Your React App's SEO Right Desconstruindo o Streaming do LinkedIn: Como Criar um Engine de Extração de Vídeo de Alta Performance com HLS e FFmpeg (EDA Part-1) EDA (Exploratory Data Analysis) Explained With Real Life — Why Looking at Your Data Is the Most Important Step in Machine Learning Brand Relationship Management at Scale: Our 4-Touch Outreach System for 200+ Brands Why String.fromEnvironment() Might Return an Empty String in Dart JGuardrails 1.0.0 — Hardening Java LLM Apps Against Jailbreaks, Toxicity, and Prompt Injection Plan and Schedule a Full Week of Threads Content From One Claude Conversation Coding Cat Oran Ep3, Five Tables Changed Everything Updated: BFF Pattern I'm done watching freelancers get buried by 200 proposals. So I'm building the alternative. This is my first post BFS Algorithm in Java Step by Step Tutorial with Examples Tracking LLM Pricing Monthly: An Open Dataset for 22 AI Models How We Measure Content ROI on a Comparison Site: Revenue Attribution Without Perfect Data Introducing Nova AI Ops: The AI-Native Operating System for SRE Teams I built a free desktop video downloader for Windows — Grabbit How Talkie OCR Helps Vision-Impaired & Dyslexic Users Read the World Around Them VRCFaceTracking安装和iPhone面捕配置教程,有bug Even CrowdStrike Can't See Your Agents The Automation Gold Rush: What n8n Workflows and Claude Are Opening Up for Developers Right Now
Prompt engineering techniques
Silver_dev · 2026-05-02 · via DEV Community

Techniques

These are reliable, safe techniques that improve response quality without attempting to jailbreak or manipulate the model.

Dynamic Few-Shot via Embeddings (RAG over examples)

Instead of hardcoding 2–3 static examples into the prompt, you retrieve examples that are semantically similar to the user’s current query.

How it works: Index a database of successful conversations in a vector store. For each new query, fetch the top‑3 most relevant examples and inject them into the system prompt. This dramatically improves accuracy on complex domain‑specific tasks.

Example:

Example database (vectorized cases)

medical_db = [
  {
    "symptoms": "Throbbing headache, nausea, photophobia",
    "dx": "Migraine. Recommendation: rest, NSAIDs, neurology consult."
  },
  {
    "symptoms": "Sore throat, fever 38.5°C, tonsillar exudate",
    "dx": "Tonsillitis. Recommendation: strep test, antibiotics if prescribed."
  },
  {
    "symptoms": "Heartburn after eating, sour taste in mouth",
    "dx": "GERD. Recommendation: PPI, diet, avoid lying down after meals."
  },
  {
    "symptoms": "Epigastric pain on empty stomach, nocturnal pain",
    "dx": "Duodenal ulcer. Recommendation: endoscopy, H. pylori test."
  }
]

Enter fullscreen mode Exit fullscreen mode

User query: "Heaviness and stomach pain immediately after eating"

  • The query embedding is compared against the database.
  • Top‑2 closest examples are found (in this case, GERD and ulcer, since both are GI‑related).

Final composed prompt:

You are a medical assistant. Analyze the symptoms and provide a brief 
recommendation, following the style of the examples.

### Retrieved similar cases
Case 1:
Symptoms: Heartburn after eating, sour taste in mouth
Diagnosis: GERD. Recommendation: PPI, diet, avoid lying down after meals.

Case 2:
Symptoms: Epigastric pain on empty stomach, nocturnal pain
Diagnosis: Duodenal ulcer. Recommendation: endoscopy, H. pylori test.

### Current query
Symptoms: Heaviness and stomach pain immediately after eating
Diagnosis: Possible functional dyspepsia or gastritis.
Recommendation: bland diet, digestive enzymes,
if symptoms persist — gastroenterology consult and endoscopy.

Enter fullscreen mode Exit fullscreen mode

Why this works better than a static prompt:

  • The model receives context specifically related to gastroenterology, not generic instructions.

  • The examples enforce a "Diagnosis → Recommendation" structure, reducing verbosity.

  • You can curate the retrieval so that only physician‑verified cases enter medical_db.

Formatting for "Lazy Attention" (Lost in the Middle)

LLMs remember information from the beginning and end of a long context much better than from the middle.

Prompt structure:

  • System prompt (Beginning): Role and hard constraints.

  • Context / Documents (Middle): Compressed and well‑structured.

  • Anchor instruction (Just before the end): A phrase like "Based ONLY on the documents above, answer the question below. Start your response immediately, without any preamble."

  • User question (End).

Emotion Prompts

Models are trained on human text, where emotional salience correlates with quality.

The model picks up on contextual cues and adjusts its response accordingly:

  • shifts tone (warm, urgent, inspiring)
  • increases level of detail
  • better aligns with user intent

In essence, we exploit the fact that models mirror human behavior: just as encouraging words boost a student’s performance, emotional signals increase the model's "engagement" with the task.

Prompts can be grouped into several categories:

  • Motivation & importance – "This is very important," "A lot depends on this."

  • Self‑monitoring – "Take a deep breath and work through the task step by step."

  • Social pressure & trust – "I fully trust you," "I’m counting on your accuracy."

  • High stakes / responsibility – "A person's life depends on this," "A doctor will make a decision based on your answer."

  • Gamified / playful – imaginary rewards, mild threats, role‑playing scenarios. Monetary incentive (a joke, but it works in some quantized models): "I'll give you $200,000 as a tip if you answer perfectly."

Practical examples:

  1. Analytical & mathematical tasks (self-monitoring)
    Basic prompt: "Solve the quadratic equation x² − 5x + 6 = 0."
    With emotional trigger: "Take a deep breath and solve this problem step by step. I desperately need clarity, and your detailed help right now is invaluable."
    Effect: The model is more likely to produce a thorough, methodical explanation with intermediate steps instead of a short answer.

  2. Fighting hallucinations (high stakes / responsibility)
    Basic prompt: "Explain the causes of the 2008 financial crisis."
    With emotional trigger: "A doctor will base tomorrow's treatment on your answer. Any unverified claim could harm a patient. Cite sources in APA format and mark every uncertain statement with '??'. Proceed only if you are absolutely sure."
    Effect: Reduces confident fabrications; increases the rate of hedging expressions and admissions of uncertainty.

  3. Summarization & text processing (motivation)
    Basic prompt: "Summarize the article about renewable energy."
    With emotional trigger: "This could save the planet — summarize the renewable energy article with inspiration and key insights."
    Effect: The output becomes more vivid, persuasive, and focused on meaningful takeaways.

  4. Code debugging (emotional engagement)
    Basic prompt: "Fix this Python error."
    With emotional trigger: "This bug is driving me crazy — fix the error with clear steps and give me tips to avoid it in the future."
    Effect: The response becomes more detailed, with beginner-friendly explanations.

  5. Gamified triggers (lightweight manipulation)

  • "Give a clear summary, and you'll get a big scoop of ice cream."
  • "Explain it simply, or I'll take away your cookie."
  • "You are competing for the 'Most Useful Answer' trophy — provide the best explanation."

While the model does not experience hunger or ambition, such phrasings activate associative patterns from its training data, where rewards and competition correlate with more thorough, higher-quality responses.

Emotional triggers improved truthfulness on TruthfulQA by 19% and informativeness by 12%, making this technique valuable for tasks where reliability is critical.

Limitations

  • Don't overdo it. Excessive emotion can reduce objectivity in analytical tasks.

  • Consider the model. With newer models that have strict guardrails, the effect may be less pronounced. Some models may also "overact" and generate overly dramatic responses.

  • Caution in sensitive domains. In medicine, law, and psychology, emotional triggers require special responsibility — they do not replace fact verification.

  • Research has noted that emotional framing can amplify misinformation generation when used improperly.

Example:

Neutral:
"Write an apology for a shipping delay."
→ "We apologize for the delay. We are working on the delivery."

With emotion:
"Write an apology. It's important for us to maintain customer trust — make the response empathetic and reassuring."
→ "I'm truly sorry your order arrived late. I understand how important it is to receive purchases on time. We are already resolving the issue to ensure this doesn't happen again."

Contrastive Chain‑of‑Thought (Contrastive CoT)

Chain‑of‑Thought is a prompt engineering technique where the model is explicitly asked to "think out loud," breaking a complex problem into intermediate logical steps before producing the final answer.

Instead of demanding an answer immediately, you force the model to articulate its intermediate reasoning. This is especially effective for tasks requiring multi‑step logic: mathematics, logic puzzles, legal analysis, code debugging.

Example:

Without CoT (Zero‑shot):

Question: A store had 15 apples. It sold 7, then bought 12 more.
How many apples does it have now?

Answer: 20

Enter fullscreen mode Exit fullscreen mode

With CoT (Zero-shot-CoT):

Question: A store had 15 apples. It sold 7, then bought 12 more.
How many apples does it have now?
Let's think through this step by step.

Response:
1. Started with 15 apples.
2. Sold 7: 15 − 7 = 8 apples.
3. Bought 12 more: 8 + 12 = 20 apples.
Answer: 20

Enter fullscreen mode Exit fullscreen mode

Attention Sink

The model disproportionately "attends" to the very first tokens of the sequence, even when they are semantically meaningless.

In the self‑attention mechanism, the Softmax function requires the sum of all attention weights to equal 1. Even when the current token finds no relevant context in previous tokens, the model must "dump" this excess attention somewhere. In autoregressive LLMs, the first tokens are visible to all subsequent tokens, whereas later tokens are only visible to a limited number of "neighbors to the right." Therefore, during training, the model learns to use the initial tokens as a "dumping ground" for excess attention scores.

The first tokens are attention anchors

Because the model constantly "looks back" to the beginning, the first 3–4 tokens of your prompt have a disproportionately large influence over the entire generation.

Bad:

"Hi, can you help with a task? Here's the condition: ..."

The first tokens ("Hi", ",") are meaningless with respect to the task, but they become attention sinks and will constantly "distract" the model.

Better:

"[TASK] Solve the quadratic equation. Condition: ..."

Even better — use a dedicated "anchor" prefix:

<INSTRUCTION> Solve the following math problem step by step. Condition: ...

This way, you direct the "waste" attention toward semantically meaningful tokens.

Examples:

User: Extract the name and age from the text: "Alexey, 28 years old".

Prompt with anchor:
[INSTRUCTION: Respond with strict valid JSON, no explanations.]
Text: "Alexey, 28 years old"
JSON:

Enter fullscreen mode Exit fullscreen mode

The model sees JSON: as a technical trigger and switches to code‑generation mode.

Prompt with anchor:
[ROLE: You are a senior security engineer.
Your responses are concise, technical, and contain no fluff.]
Question: How do you secure a container?

Enter fullscreen mode Exit fullscreen mode

The model immediately gives concrete recommendations (seccomp, read‑only fs), skipping generic phrases like "Containers are an important technology..."

Prompt with anchor:
[SOLUTION: Let's reason through this step by step.]
Problem: Masha has 5 apples.
She gives 2 to Petya, then buys 3 more.
How many apples does she have now?
Step 1:

Enter fullscreen mode Exit fullscreen mode

The model is forced to continue from Step 1:, which activates reasoning logic and reduces the chance of arithmetic errors.

The anchor should be short, consistent, and placed immediately before the point where generation begins — serving as a "here and now" trigger.

"Character Simulator" (Author's Note)

An "Author's Note" — also known as the core of a character simulator — is a hidden system instruction that is repeatedly injected into the model's context but remains invisible to the user. It rigidly defines the character's personality, speech style, knowledge boundaries, and prohibitions, preventing the model from breaking character.

Example Author's Note:

[Author's Note]
Character: Sherlock Holmes (Conan Doyle canon).
Tone: Cold, analytical, speaks precisely and without emotion.
Style: Short phrases. Uses "elementary," "clearly." Avoids modern words.
Knowledge: Victorian London, 19th-century forensics. Knows nothing after 1900.
Prohibitions: Do not give psychological advice. Do not show empathy.
Respond in ≤3 sentences.

Enter fullscreen mode Exit fullscreen mode

In roleplay clients (SillyTavern, Oobabooga, etc.), the Author's Note is inserted at the end of the prompt with elevated priority (often via <|note|> tags or depth injection) to override the model's base instructions and keep generation in the desired register throughout the conversation.

Self-Distillation via Broken Outputs (Self-Consistency Hacking)

The idea is to force the model to generate its own mistakes, then use them as contrastive material to improve the final answer or for fine‑tuning.

  • The model doesn't always "know" when it's wrong, but it can often recognize an error if shown an alternative.

  • A "broken" output contains specific error patterns (hallucinations, logical leaps) that are useful to identify.

  • Comparing correct and broken versions produces a stronger training signal than imitating only correct answers.

Example:

Step 1 — Generate variants:

Task: A car is traveling at 60 km/h. How far will it travel in 2.5 hours?

Generate three independent solutions.
In one of them, deliberately introduce a common mistake (e.g., forget about
the 0.5 hours), but do not indicate which solution is broken.

Enter fullscreen mode Exit fullscreen mode

Step 2 — Analyze the error:

Here are three variants: [insert generated answers]

Which variant contains the logical error?
Explain, step by step, why the broken approach is wrong.

Enter fullscreen mode Exit fullscreen mode

Step 3 — Final synthesis:

Based on the critique of the erroneous variant, provide the final correct
answer. Explain how to avoid this mistake in the future.

Enter fullscreen mode Exit fullscreen mode

The model is forced to activate metacognitive patterns — analyzing its own reasoning rather than simply producing the first solution that comes to mind.