llamaguard
できること
このスキルは、テキストが安全か安全でないかを分類するMetaのモデルであるLlamaGuardを説明します。AIアプリへの入力と出力を絞り込みたい開発者に向けたものです。
使う場面
- ✓ユーザーのメッセージを、メインの言語モデルに届く前に確認したいとき。
- ✓ユーザーに表示する前に、モデルの返答を確認したいとき。
- ✓暴力、武器、自傷、犯罪の計画を検出する調整の工程が必要なとき。
スキルのリンク
https://github.com/Orchestra-Research/AI-Research-SKILLs/blob/main/07-safety-alignment/llamaguard/SKILL.mdコピーしてAI(Claude、ChatGPT、Cursor)に貼り付け、指示に従うよう頼んでください。
使い方
いちばん簡単な方法:メッセージをコピーしてAIに貼り付けるだけ。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エージェントが、Metaの小さな分類器を使い、AIアプリに届く前のテキストにプロンプトインジェクションやジェイルブレイクの試みがないか確認できるよう支援します。
pytorch-fsdp2
14kエージェントが、大規模なモデルを複数のGPUに分割して正しく保存できるよう、PyTorchのFSDP2を学習スクリプトに追加する方法を示します。
ml-training-recipes
14kエージェントが、モデルの選択、オプティマイザー、学習率、損失の急上昇への対処を含む、ニューラルネットワーク学習の実証済みの手順を使えるよう支援します。
似ているスキル
reverse-engineer-anything
422kREAツールを使って、出荷済みのアプリやパッケージの中身を調べ、機能の説明、版の比較、再構築の手順をエージェントが支援します。
1password
394k1Password CLIをセットアップし、サインインして、秘密情報の値を会話に表示せずに読み取ったり注入したりするようエージェントを支援します。
healthcheck
394kOpenClawを動かすコンピューターやサーバーを、SSH、ファイアウォール、更新、バックアップなどのセキュリティリスクについて監査し、安全な修正案を提案するようエージェントを支援します。