Zum Hauptinhalt springen
Echtzeit-Radar & Feeds
Alle RSS Feeds ➔
👥 Community & Social
Windows Tipps & SecurityGrafikkarte vor Überhitzung schützen: So geht’s(25.09.2026 um 08:00 Uhr)
••••••••••
Windows Tipps & SecurityGrafikkarte vor Überhitzung schützen: So geht’s(25.09.2026 um 08:00 Uhr)
••••••••••
Intelligence View
⚡ tsecurity.de Intelligence

Type-safe LLM prompts in Rust: catching prompt bugs before they happen

Here's a bug I've seen in production more than once: prompt = template.format(document=doc, language=lang, tone=tone) And somewhere upstream, tone wasn't passed. Python doesn't tell you. The LLM gets a prompt with a literal {tone}…

0
↗ Quelle (dev.to)
Reagiere als Erste:r — dein Feedback zählt!

Here's a bug I've seen in production more than once:




prompt = template.format(document=doc, language=lang, tone=tone)






And somewhere upstream, tone wasn't passed. Python doesn't tell you. The LLM gets a prompt with a literal {tone} in it. It either ignores it, makes something up, or returns garbage. You find out when a user complains.



Rust can do better. Here's the same thing in prompt-rs:




let prompt = PromptTemplate::new("Summarize {document} in {language} with a {tone} tone")
.fill("document", &doc)
.fill("language", "English")
// forgot tone
.build()?; // Returns Err("Missing required variable(s): tone")






You get a Result. You handle it explicitly. The bug surfaces at the call site, not in production.




GitHub: LakshmiSravyaVedantham/prompt-rs










Install






[dependencies]
prompt-rs = "0.1"
serde_json = "1" # for Chat serialization












Prompt templates






use prompt_rs::PromptTemplate;

let template = PromptTemplate::new("Summarize {document} in {language}");

// Inspect what variables the template expects
let vars = template.variables();
// HashSet { "document", "language" }

// Fill them in and build
let prompt = template
.fill("document", &my_doc)
.fill("language", "English")
.build()?;
// "Summarize [doc content] in English"






If you miss a variable:




let result = template.fill("document", &my_doc).build();
// Err(MissingVariables("language"))






The error message tells you exactly which variable you forgot. No guessing.









Chat messages



The Chat builder produces Vec<Message> in the exact format OpenAI and Anthropic expect:




use prompt_rs::chat::Chat;

let messages = Chat::new()
.system("You are a concise technical writer")
.user(&prompt)
.build();

// Serialize directly — messages are serde::Serialize
let body = serde_json::json!({
"model": "gpt-4o",
"messages": messages,
"max_tokens": 512
});






The Role enum serializes to lowercase strings ("system", "user", "assistant") matching the OpenAI/Anthropic API format exactly:




pub enum Role {
System,
User,
Assistant,
}
// serde: { "role": "user", "content": "..." }












How it works internally



The template parser is 30 lines of plain Rust — no regex, no proc macros:




pub fn variables(&self) -> HashSet<&str> {
let mut vars = HashSet::new();
let mut rest = self.template.as_str();
while let Some(start) = rest.find('{') {
rest = &rest[start + 1..];
if let Some(end) = rest.find('}') {
let name = &rest[..end];
if !name.is_empty() && name.chars().all(|c| c.is_alphanumeric() || c == '_') {
vars.insert(name);
}
rest = &rest[end + 1..];
} else {
break;
}
}
vars
}






It scans for {...} pairs, validates that the name is alphanumeric (so {1} and {a b} are ignored), and deduplicates via HashSet. Then build() checks that every discovered variable has a value:




pub fn build(self) -> Result<String, PromptError> {
let vars = self.template.variables();
let missing: Vec<&str> = vars.iter()
.filter(|v| !self.values.contains_key(*v))
.copied().collect();

if !missing.is_empty() {
return Err(PromptError::MissingVariables(missing.join(", ")));
}

let mut result = self.template.template.clone();
for (key, val) in &self.values {
result = result.replace(&format!("{{{key}}}"), val);
}
Ok(result)
}






The whole library is ~150 lines. You can read all of it in 5 minutes.









Why not a proc macro?



I considered making prompt! a compile-time macro so missing variables would be a compiler error rather than a runtime Result. That would be even better.



But it adds significant complexity (proc macros require a separate crate, the syntax gets weird), and most prompt templates are built from runtime data — you can't know at compile time what document will contain. So Result<String, PromptError> is the right boundary: compile time can't check it, but at least runtime checks it explicitly before the API call.









Part of a series



This is the third in a series of minimal Rust AI tools:





  1. nano-rag — RAG in 300 lines, no LangChain


  2. llm-bench — benchmark OpenAI vs Claude vs Groq


  3. prompt-rs — this one



All three follow the same philosophy: the smallest complete thing that does the real thing, with no magic hidden inside.



The code is at github.com/LakshmiSravyaVedantham/prompt-rs.

1. Sofort-Triage & Abwehrmaßnahmen

SOC Incident Playbook: Vulnerability Remediation & Verification
Syntax validiert (0 Fehler)
title: Detect Exploitation - Type-safe LLM prompts in Rust: catching prompt bugs before they happen
id: b359e278-8a95-4fb9-9164-e9eb6ba789f1
status: experimental
description: Automatisch generierte SIEM-Erkennungsregel basierend auf CTI Intelligence
references:
  - https://tsecurity.de/
author: iShareStuff CTI Automated Detection Engine
date: 2026-09-27
logsource:
  category: network_connection
  product: any
detection:
  selection:
      CommandLine|contains:
        - 'exploit'
  condition: selection
falsepositives:
  - Legitime administrative Zugriffe oder Penetrationstests
level: high
tags:
  - attack.initial_access
Syntax validiert (0 Fehler)
rule CTI_Threat_Indicator {
    meta:
        author = "iShareStuff CTI Automated Detection Engine"
        date = "2026-09-27"
        description = "YARA Signature for "
    strings:
        $str = "Type-safe LLM prompts in Rust:" ascii wide
    condition:
        any of them
}
Syntax validiert (0 Fehler)
index=security sourcetype IN ("cisco:asa", "pan:traffic", "zeek_conn", "suricata", "WinEventLog:Security")
("Type-safe LLM prompts in Rust catching p")
| stats count earliest(_time) as first_seen latest(_time) as last_seen by src_ip, dest_ip, dest_host, signature
| eval first_seen=strftime(first_seen, "%Y-%m-%d %H:%M:%S"), last_seen=strftime(last_seen, "%Y-%m-%d %H:%M:%S")
| sort - count
Syntax validiert (0 Fehler)
message: "*Type-safe LLM prompts in Rust catching p*"
Syntax validiert (0 Fehler)
CommonSecurityLog
| where Message has "Type-safe LLM prompts in Rust catching p"
| summarize EventCount = count(), FirstSeen = min(TimeGenerated), LastSeen = max(TimeGenerated) by SourceIP, DestinationIP, DestinationPort, Activity
| extend DetectionRule = "iShareStuff-CTI-Compiled"
| sort by EventCount desc

2. Cyber Threat Intelligence & Forensik

🎯
MITRE ATT&CK Matrix Navigator 14 Taktiken
Reconnaissance
-
Resource Development
-
Initial Access
Execution
Persistence
-
Privilege Escalation
Defense Evasion
Credential Access
-
Discovery
-
Lateral Movement
-
Collection
-
Command and Control
Exfiltration
-
Impact
tsecurity.de Cognitive Threat RAG
Fokus-Vektor:

Analyse für identifizierte Bedrohung auf Basis von Live-CTI (ENISA EUVD): CVSS 0.0 · EPSS 0.0% · CISA KEV: nein. Handlungsableitung aus den verlinkten Hersteller-Quellen.

🛡️ Angriffsfläche & Exposure

Netzwerk/Remote-Zugriff ohne Vorauthentifizierung möglich.

⚡ Empfohlene Sofortmaßnahmen
  • 1. Perimeter-Inspektion: Relevante Portfreigaben und exponierte Endpunkte unverzüglich scannen.
  • 2. Patch-Applikation: Hersteller-Hotfix einspielen oder betroffene Daemons in isolierte DMZ-Segmente überführen.
  • 3. Telemetrie & EDR-Alerts: Prozessaufrufe und Child-Processes auf anomale Shell-Spawns überwachen.
Ähnliche Beiträge
🔍 Verwandte News

Auch interessante Nachrichten Type-safe LLM prompts in Rust: catching prompt bugs before they happen

Thematisch verwandte Begriffe: Typesafe, prompts, Rust, catching · 6 Treffer

Laden...

Videos werden geladen ...

Laden...

Beiträge werden geladen ...

Laden...

Videos werden geladen ...

Laden...

Beiträge werden geladen ...

Laden...

Videos werden geladen ...

Laden...

Beiträge werden geladen ...

Laden...

Videos werden geladen ...

Laden...

Beiträge werden geladen ...

Laden...

Videos werden geladen ...

💬 Kommentare werden geladen…
Zum Aktualisieren ziehen
ZERO-DAY CVE-2026-100620 | Capgo CLI (npm package @capgo/cli) through 7.98.2 is affected by an ove…
Advisory →
tsecurity.de Icon
Offline-Lesen, Eilmeldungen & 0ms Ladezeit

Installiere tsecurity.de direkt auf deinen Home-Bildschirm für das ultimative Vollbild-Magazinerlebnis ohne Browser-Leisten.

Nächster Beitrag