Skip to main content
A ready-to-run example is available here!

Overview

Hooks let you observe and customize key lifecycle moments in the SDK without forking core code. Typical uses include:
  • Logging and analytics
  • Emitting custom metrics
  • Auditing or compliance
  • Tracing and debugging

Hook Types

Exit Codes

Hook scripts signal their result through their exit code. The SDK matches the Claude Code hook contract:
  • 0 — success. The operation proceeds. stdout is parsed as JSON for structured output (decision, reason, additionalContext, continue).
  • 2 — block. The operation is denied. For PreToolUse and UserPromptSubmit this rejects the action; for Stop it prevents the agent from finishing and the conversation continues. stderr / reason is surfaced as feedback.
  • Any other non-zero exit code — non-blocking error. success is set to False and the error is logged via HookExecutionEvent, but the operation still proceeds.
Only exit code 2 blocks. Exit code 1 (the conventional Unix failure code) is treated as a non-blocking error. A hook intended to enforce a policy must exit with 2.

Key Concepts

  • Registration points: subscribe to events or attach pre/post hooks around LLM calls and tool execution
  • Isolation: hooks run outside the agent loop logic, avoiding core modifications
  • Composition: enable or disable hooks per environment (local vs. prod)

Ready-to-run Example

This example is available on GitHub: examples/01_standalone_sdk/33_hooks
examples/01_standalone_sdk/33_hooks/main.py
You can run the example code as-is.
The model name should follow the LiteLLM convention: provider/model_name (e.g., anthropic/claude-sonnet-4-5-20250929, openai/gpt-4o). The LLM_API_KEY should be the API key for your chosen provider.
ChatGPT Plus/Pro subscribers: You can use LLM.subscription_login() to authenticate with your ChatGPT account and access Codex models without consuming API credits. See the LLM Subscriptions guide for details.

Hook Scripts

The example uses external hook scripts in the hook_scripts/ directory:

Next Steps