็™ป้Œฒใ—ใฆๆ‹›ๅพ…ใƒชใƒณใ‚ฏใ‚’ๅ…ฑๆœ‰ใ™ใ‚‹ใจใ€ๅ‹•็”ปๅ†็”Ÿๅ ฑ้…ฌใจ็ดนไป‹ๅ ฑ้…ฌใ‚’็ฒๅพ—ใงใใพใ™ใ€‚

cv usk
@cv_usk
AI / Software Research Notes AI Agent, LLMOps, MLOps, Software Architecture ๆŠ•็จฟใฏๅ€‹ไบบใฎๆ„่ฆ‹ใงใ™ใ€‚
ๅ‚ๅŠ  May 2026
258 ใƒ•ใ‚ฉใƒญใƒผไธญ    228 ใƒ•ใ‚กใƒณ
# Practical and Useful Patterns for OpenAI Agent SDK ๐ŸŒ Can you see what is happening inside your agent? Lifecycle hooks let you transparently embed logging, auditing, and performance optimization into agent behavior. RunHooks and AgentHooks let you inject custom logic at agent start/end, LLM calls, tool execution, and handoff events. ๐Ÿ“Œ Title: Agents -- Lifecycle events (hooks) ๐Ÿ”— URL: ๐Ÿงฉ Overview The OpenAI Agent SDK provides a hook mechanism for executing custom code at each stage of an agent's lifecycle. `RunHooks` apply to the entire workflow, while `AgentHooks` apply to specific agents. Available hooks include `on_agent_start`/`on_agent_end`, `on_llm_start`/`on_llm_end`, `on_tool_start`/`on_tool_end`, and `on_handoff`. Use them to implement logging, metrics collection, audit trails, and data prefetching. ๐Ÿ›  How to Use Define a `LoggingHooks` class extending `RunHooks`, overriding `async def on_agent_start(self, context, agent)` and `async def on_agent_end(self, context, agent, output)` to log agent lifecycle events. Create an `Agent` and pass the hooks instance via ` "Hello", run_hooks=LoggingHooks())`. ๐Ÿ— Practical Usage Patterns **Output Item Count Logging with on_llm_end, Token Usage Logging with on_agent_end** Combine workflow-wide RunHooks with agent-specific AgentHooks for comprehensive monitoring. `MetricsRunHooks` extends `RunHooks` and logs `total_tokens` and `prompt_tokens` in `on_agent_end` for workflow-wide cost monitoring. `DetailedAgentHooks` extends `AgentHooks` and logs the output item count from `response.output` in `on_llm_end` for agent-specific monitoring. Apply agent-level hooks via `Agent(hooks=DetailedAgentHooks())` and workflow-level hooks via ` ..., run_hooks=MetricsRunHooks())` for comprehensive observability. **Audit Logging and Distributed Tracing with on_tool_start ToolContext** Record trace information before and after tool execution to simplify incident investigation. `AuditHooks` extends `AgentHooks` and implements `on_tool_start` to log `context.context.trace_id`, ` ` and a UTC timestamp for distributed tracing. In `on_tool_end`, it logs the same `trace_id` and ` along with a success check (`result is not None`) to complete the audit trail. **Data Prefetching on Handoff for Latency Reduction** Pre-fetch data needed by the target agent during handoff to improve response times. `PrefetchHooks` extends `RunHooks` and implements `on_handoff` to check if ` is `"OrderSupportAgent"`. When matched, it calls `await db.fetch_orders( and `await db.fetch_payment_methods( to pre-load data into the user context, reducing latency for the target agent. ๐Ÿ’ก Use Cases ๐Ÿ“Š Log LLM response output item counts with on_llm_end for output quality monitoring ๐Ÿ’ฐ Log token usage with on_agent_end and feed into cost management dashboards ๐Ÿ” Automatically record audit logs and distributed traces with on_tool_start/end โšก Prefetch data on_handoff for the target agent to reduce response latency โš ๏ธ Caveats - Exceptions inside hooks can affect agent execution. Always wrap hook logic in try/except for reliable error handling. - Heavy processing in hooks increases overall agent latency. Consider async I/O or background tasks. - Be intentional about RunHooks vs AgentHooks. Use RunHooks for cross-workflow monitoring and AgentHooks for detailed monitoring of specific agents. โœจ Lifecycle hooks transform your agent from a "black box" into a fully observable system. Implement the monitoring, auditing, and optimization essential for production -- without polluting your agent logic! #OpenAIAgentSDK# #AIAgent#
ใ‚‚ใฃใจ่ฆ‹ใ‚‹