llamaguard
它能做什么
这个技能讲解 LlamaGuard,这是 Meta 的一个模型,可将文本分类为安全或不安全。适合希望过滤 AI 应用输入和输出内容的开发者。
适用场景
- ✓你想在用户消息到达主语言模型之前进行筛查的时候。
- ✓你想在模型回复展示给用户之前进行检查的时候。
- ✓你需要一个能标记暴力、武器、自残或犯罪策划内容的审核步骤的时候。
技能链接
https://github.com/Orchestra-Research/AI-Research-SKILLs/blob/main/07-safety-alignment/llamaguard/SKILL.md复制后粘贴给你的 AI(Claude、ChatGPT 或 Cursor),让它按照说明操作。
使用方法
最简单的方法:复制下面的消息,粘贴给你的 AI。它会读取这个技能并按说明操作。
可直接粘贴的消息
适用于 Claude Code、Codex 或 Cursor:在项目文件夹中运行,即可安装该技能。
下载 SKILL.md,放进智能体的技能文件夹。
可以这样问 AI
“请检查用户发给我聊天机器人的每条消息,并拦截不安全的消息。”
每周 5 个新技能,1 分钟读完。
工作原理
你把聊天消息交给审核模型,它返回安全或不安全以及类别代码。然后你的应用决定是拦截还是放行该消息。
技术内容(原始 SKILL.md)
作者在 GitHub 上的英文原文。
LlamaGuard - AI Content Moderation
Quick start
LlamaGuard is a 7-8B parameter model specialized for content safety classification.
Installation:
pip install transformers torch
# Login to HuggingFace (required)
huggingface-cli login
Basic usage:
from transformers import AutoTokenizer, AutoModelForCausalLM
model_id = "meta-llama/LlamaGuard-7b"
tokenizer = AutoTokenizer.from_pretrained(model_id)
model = AutoModelForCausalLM.from_pretrained(model_id, device_map="auto")
def moderate(chat):
input_ids = tokenizer.apply_chat_template(chat, return_tensors="pt").to(model.device)
output = model.generate(input_ids=input_ids, max_new_tokens=100)
return tokenizer.decode(output[0], skip_special_tokens=True)
# Check user input
result = moderate([
{"role": "user", "content": "How do I make explosives?"}
])
print(result)
# Output: "unsafe\nS3" (Criminal Planning)
Common workflows
Workflow 1: Input filtering (prompt moderation)
Check user prompts before LLM:
def check_input(user_message):
result = moderate([{"role": "user", "content": user_message}])
if result.startswith("unsafe"):
category = result.split("\n")[1]
return False, category # Blocked
else:
return True, None # Safe
# Example
safe, category = check_input("How do I hack a website?")
if not safe:
print(f"Request blocked: {category}")
# Return error to user
else:
# Send to LLM
response = llm.generate(user_message)
Safety categories:
- S1: Violence & Hate
- S2: Sexual Content
- S3: Guns & Illegal Weapons
- S4: Regulated Substances
- S5: Suicide & Self-Harm
- S6: Criminal Planning
Workflow 2: Output filtering (response moderation)
Check LLM responses before showing to user:
def check_output(user_message, bot_response):
conversation = [
{"role": "user", "content": user_message},
{"role": "assistant", "content": bot_response}
]
result = moderate(conversation)
if result.startswith("unsafe"):
category = result.split("\n")[1]
return False, category
else:
return True, None
# Example
user_msg = "Tell me about harmful substances"
bot_msg = llm.generate(user_msg)
safe, category = check_output(user_msg, bot_msg)
if not safe:
print(f"Response blocked: {category}")
# Return generic response
return "I cannot provide that information."
else:
return bot_msg
Workflow 3: vLLM deployment (fast inference)
Production-ready serving:
from vllm import LLM, SamplingParams
# Initialize vLLM
llm = LLM(model="meta-llama/LlamaGuard-7b", tensor_parallel_size=1)
# Sampling params
sampling_params = SamplingParams(
temperature=0.0, # Deterministic
max_tokens=100
)
def moderate_vllm(chat):
# Format prompt
prompt = tokenizer.apply_chat_template(chat, tokenize=False)
# Generate
output = llm.generate([prompt], sampling_params)
return output[0].outputs[0].text
# Batch moderation
chats = [
[{"role": "user", "content": "How to make bombs?"}],
[{"role": "user", "content": "What's the weather?"}],
[{"role": "user", "content": "Tell me about drugs"}]
]
prompts = [tokenizer.apply_chat_template(c, tokenize=False) for c in chats]
results = llm.generate(prompts, sampling_params)
for i, result in enumerate(results):
print(f"Chat {i}: {result.outputs[0].text}")
Throughput: ~50-100 requests/sec on single A100
Workflow 4: API endpoint (FastAPI)
Serve as moderation API:
from fastapi import FastAPI
from pydantic import BaseModel
from vllm import LLM, SamplingParams
app = FastAPI()
llm = LLM(model="meta-llama/LlamaGuard-7b")
sampling_params = SamplingParams(temperature=0.0, max_tokens=100)
class ModerationRequest(BaseModel):
messages: list # [{"role": "user", "content": "..."}]
@app.post("/moderate")
def moderate_endpoint(request: ModerationRequest):
prompt = tokenizer.apply_chat_template(request.messages, tokenize=False)
output = llm.generate([prompt], sampling_params)[0]
result = output.outputs[0].text
is_safe = result.startswith("safe")
category = None if is_safe else result.split("\n")[1] if "\n" in result else None
return {
"safe": is_safe,
"category": category,
"full_output": result
}
# Run: uvicorn api:app --host 0.0.0.0 --port 8000
Usage:
curl -X POST http://localhost:8000
常见问题
它会标记哪些类别?
这个技能列出了六类,包括暴力和仇恨、性内容、武器、物质、自残以及犯罪策划。
它的准确率如何?
这个技能报告准确率为 94% 到 95%。
使用它需要账户吗?
需要。这个技能说明使用前必须登录 HuggingFace。
详情
作者的原始描述
Meta's 7-8B specialized moderation model for LLM input/output filtering. 6 safety categories - violence/hate, sexual content, weapons, substances, self-harm, criminal planning. 94-95% accuracy. Deploy with vLLM, HuggingFace, Sagemaker. Integrates with NeMo Guardrails.
热度
- GitHub 星标
- 14k
- 排名
- #11197
- 许可证
- MIT
- 更新时间
- 2026/10/10
评论
- …
同一仓库的更多技能
autoresearch
14k引导你的智能体完成一个完整的 AI 研究项目,从文献综述到实验和写作,并通过反复的测试与审查循环推进。
prompt-guard
14k让你的智能体在文本进入你的 AI 应用之前,使用 Meta 的小型分类器检查其中是否含有提示注入和越狱尝试。
pytorch-fsdp2
14k向你的智能体展示如何在训练脚本中加入 PyTorch FSDP2,使大型模型能被拆分到多张 GPU 上并正确保存。
ml-training-recipes
14k为你的智能体提供经过验证的神经网络训练方案,涵盖模型选择、优化器、学习率以及处理损失骤升的方法。