Skip to main content

Slash Commands ใน SDK

เรียนรู้วิธีใช้ slash commands เพื่อควบคุม Claude Code sessions ผ่าน SDK

Slash commands เป็นวิธีควบคุม Claude Code sessions ด้วยคำสั่งพิเศษที่ขึ้นต้นด้วย / คำสั่งเหล่านี้สามารถส่งผ่าน SDK เพื่อทำการกระทำต่างๆ เช่น การย่อ context, การแสดงรายการการใช้งาน context, หรือการเรียกใช้คำสั่ง custom เฉพาะคำสั่งที่ทำงานโดยไม่มี interactive terminal เท่านั้นที่สามารถ dispatch ผ่าน SDK ได้ message system/init จะแสดงรายการที่พร้อมใช้งานในเซสชันของคุณ

การค้นพบ Slash Commands ที่พร้อมใช้งาน

Claude Agent SDK ให้ข้อมูลเกี่ยวกับ slash commands ที่พร้อมใช้งานใน system initialization message เข้าถึงข้อมูลนี้เมื่อเซสชันของคุณเริ่มต้น:

import { query } from "@anthropic-ai/claude-agent-sdk";

for await (const message of query({
prompt: "Hello Claude",
options: { maxTurns: 1 }
})) {
if (message.type === "system" && message.subtype === "init") {
console.log("Available slash commands:", message.slash_commands);
// Example output: ["clear", "compact", "context", "usage"]
}
}
import asyncio
from claude_agent_sdk import query, ClaudeAgentOptions, SystemMessage


async def main():
async for message in query(prompt="Hello Claude", options=ClaudeAgentOptions(max_turns=1)):
if isinstance(message, SystemMessage) and message.subtype == "init":
print("Available slash commands:", message.data["slash_commands"])
# Example output: ["clear", "compact", "context", "usage"]


asyncio.run(main())

การส่ง Slash Commands

ส่ง slash commands โดยรวมไว้ใน prompt string เหมือนกับข้อความปกติ:

import { query } from "@anthropic-ai/claude-agent-sdk";

// Send a slash command
for await (const message of query({
prompt: "/compact",
options: { maxTurns: 1 }
})) {
if (message.type === "result" && message.subtype === "success") {
console.log("Command executed:", message.result);
}
}
import asyncio
from claude_agent_sdk import query, ClaudeAgentOptions, ResultMessage


async def main():
# Send a slash command
async for message in query(prompt="/compact", options=ClaudeAgentOptions(max_turns=1)):
if isinstance(message, ResultMessage):
print("Command executed:", message.result)


asyncio.run(main())

Slash Commands ทั่วไป

/compact - ย่อประวัติการสนทนา

คำสั่ง /compact ลดขนาดประวัติการสนทนาของคุณโดยสรุปข้อความเก่าในขณะที่รักษา context ที่สำคัญไว้:

import { query } from "@anthropic-ai/claude-agent-sdk";

for await (const message of query({
prompt: "/compact",
options: { maxTurns: 1 }
})) {
if (message.type === "system" && message.subtype === "compact_boundary") {
console.log("Compaction completed");
console.log("Pre-compaction tokens:", message.compact_metadata.pre_tokens);
console.log("Trigger:", message.compact_metadata.trigger);
}
}
import asyncio
from claude_agent_sdk import query, ClaudeAgentOptions, SystemMessage


async def main():
async for message in query(prompt="/compact", options=ClaudeAgentOptions(max_turns=1)):
if isinstance(message, SystemMessage) and message.subtype == "compact_boundary":
print("Compaction completed")
print("Pre-compaction tokens:", message.data["compact_metadata"]["pre_tokens"])
print("Trigger:", message.data["compact_metadata"]["trigger"])


asyncio.run(main())

/clear - รีเซ็ต context การสนทนา

คำสั่ง /clear รีเซ็ตการสนทนาเป็น context ว่างเปล่า ดังนั้น prompt ถัดมาจะเริ่มต้นโดยไม่มีประวัติการสนทนาก่อนหน้า การสนทนาก่อนหน้ายังคงอยู่บนดิสก์และสามารถกลับมาได้โดยส่ง session ID ให้กับ option resume

สิ่งนี้มีประโยชน์ใน streaming input mode ซึ่งคุณส่ง prompt หลายรายการผ่านการเชื่อมต่อเดียว สำหรับการเรียก query() แบบ one-shot แต่ละครั้งเริ่มต้นด้วย context ว่างเปล่าอยู่แล้ว ดังนั้นการส่ง /clear ไม่มีผลในทางปฏิบัติ; ให้เริ่ม query() ใหม่แทน

note

/clear ใน SDK ต้องใช้ Claude Code v2.1.117 หรือใหม่กว่า ในเวอร์ชันเก่าจะไม่อยู่ใน slash_commands

การสร้าง Slash Commands แบบ Custom

นอกจากการใช้ slash commands ในตัว คุณยังสามารถสร้างคำสั่ง custom ของตัวเองที่พร้อมใช้งานผ่าน SDK ได้ คำสั่ง custom ถูกกำหนดเป็นไฟล์ markdown ในไดเรกทอรีเฉพาะ

note

ไดเรกทอรี .claude/commands/ เป็นรูปแบบ legacy รูปแบบที่แนะนำคือ .claude/skills/<name>/SKILL.md ซึ่งรองรับทั้ง slash-command invocation (/name) และการเรียกใช้อัตโนมัติโดย Claude ดู Skills สำหรับรูปแบบปัจจุบัน CLI ยังคงรองรับทั้งสองรูปแบบ

ตำแหน่งไฟล์

Slash commands แบบ custom จัดเก็บในไดเรกทอรีที่กำหนดตามขอบเขตการใช้งาน:

  • คำสั่งของโปรเจกต์: .claude/commands/ - ใช้ได้เฉพาะในโปรเจกต์ปัจจุบัน (legacy; แนะนำให้ใช้ .claude/skills/)
  • คำสั่งส่วนตัว: ~/.claude/commands/ - ใช้ได้ในทุกโปรเจกต์ของคุณ (legacy; แนะนำให้ใช้ ~/.claude/skills/)

รูปแบบไฟล์

คำสั่ง custom แต่ละรายการเป็นไฟล์ markdown ที่:

  • ชื่อไฟล์ (ไม่มีนามสกุล .md) จะกลายเป็นชื่อคำสั่ง
  • เนื้อหาของไฟล์กำหนดว่าคำสั่งทำอะไร
  • YAML frontmatter เพิ่มเติมให้ configuration

ตัวอย่างพื้นฐาน

สร้าง .claude/commands/refactor.md:

Refactor the selected code to improve readability and maintainability.
Focus on clean code principles and best practices.

สิ่งนี้สร้างคำสั่ง /refactor ที่คุณสามารถใช้ผ่าน SDK

พร้อม Frontmatter

สร้าง .claude/commands/security-check.md:

---
allowed-tools: Read, Grep, Glob
description: Run security vulnerability scan
model: claude-opus-4-7
---

Analyze the codebase for security vulnerabilities including:
- SQL injection risks
- XSS vulnerabilities
- Exposed credentials
- Insecure configurations

การใช้ Custom Commands ใน SDK

เมื่อกำหนดใน filesystem แล้ว คำสั่ง custom จะพร้อมใช้งานผ่าน SDK โดยอัตโนมัติ:

import { query } from "@anthropic-ai/claude-agent-sdk";

// Use a custom command
for await (const message of query({
prompt: "/refactor src/auth/login.ts",
options: { maxTurns: 3 }
})) {
if (message.type === "assistant") {
console.log("Refactoring suggestions:", message.message);
}
}

// Custom commands appear in the slash_commands list
for await (const message of query({
prompt: "Hello",
options: { maxTurns: 1 }
})) {
if (message.type === "system" && message.subtype === "init") {
// Will include both built-in and custom commands
console.log("Available commands:", message.slash_commands);
// Example: ["clear", "compact", "context", "usage", "refactor", "security-check"]
}
}
import asyncio
from claude_agent_sdk import query, ClaudeAgentOptions, AssistantMessage, SystemMessage


async def main():
# Use a custom command
async for message in query(
prompt="/refactor src/auth/login.py", options=ClaudeAgentOptions(max_turns=3)
):
if isinstance(message, AssistantMessage):
for block in message.content:
if hasattr(block, "text"):
print("Refactoring suggestions:", block.text)

# Custom commands appear in the slash_commands list
async for message in query(prompt="Hello", options=ClaudeAgentOptions(max_turns=1)):
if isinstance(message, SystemMessage) and message.subtype == "init":
# Will include both built-in and custom commands
print("Available commands:", message.data["slash_commands"])
# Example: ["clear", "compact", "context", "usage", "refactor", "security-check"]


asyncio.run(main())

ฟีเจอร์ขั้นสูง

Arguments และ Placeholders

คำสั่ง custom รองรับ arguments แบบ dynamic โดยใช้ placeholders:

สร้าง .claude/commands/fix-issue.md:

---
argument-hint: [issue-number] [priority]
description: Fix a GitHub issue
---

Fix issue #$0 with priority $1.
Check the issue description and implement the necessary changes.

ใช้ใน SDK:

import { query } from "@anthropic-ai/claude-agent-sdk";

// Pass arguments to custom command
for await (const message of query({
prompt: "/fix-issue 123 high",
options: { maxTurns: 5 }
})) {
// Command will process with $0="123" and $1="high"
if (message.type === "result" && message.subtype === "success") {
console.log("Issue fixed:", message.result);
}
}

การเรียกใช้ Bash Command

คำสั่ง custom สามารถรัน bash commands และรวม output ของมัน:

สร้าง .claude/commands/git-commit.md:

---
allowed-tools: Bash(git add *), Bash(git status *), Bash(git commit *)
description: Create a git commit
---

## Context

- Current status: !`git status`
- Current diff: !`git diff HEAD`

## Task

Create a git commit with appropriate message based on the changes.

ตัวอย่างในทางปฏิบัติ

คำสั่ง Code Review

สร้าง .claude/commands/code-review.md:

---
allowed-tools: Read, Grep, Glob, Bash(git diff *)
description: Comprehensive code review
---

## Changed Files
!`git diff --name-only HEAD~1`

## Detailed Changes
!`git diff HEAD~1`

## Review Checklist

Review the above changes for:
1. Code quality and readability
2. Security vulnerabilities
3. Performance implications
4. Test coverage
5. Documentation completeness

Provide specific, actionable feedback organized by priority.

คำสั่ง Test Runner

สร้าง .claude/commands/test.md:

---
allowed-tools: Bash, Read, Edit
argument-hint: [test-pattern]
description: Run tests with optional pattern
---

Run tests matching pattern: $ARGUMENTS

1. Detect the test framework (Jest, pytest, etc.)
2. Run tests with the provided pattern
3. If tests fail, analyze and fix them
4. Re-run to verify fixes

ใช้คำสั่งเหล่านี้ผ่าน SDK:

import { query } from "@anthropic-ai/claude-agent-sdk";

// Run code review
for await (const message of query({
prompt: "/code-review",
options: { maxTurns: 3 }
})) {
// Process review feedback
}

// Run specific tests
for await (const message of query({
prompt: "/test auth",
options: { maxTurns: 5 }
})) {
// Handle test results
}

ดูเพิ่มเติม