注册并分享邀请链接,可获得视频播放与邀请奖励。

cv usk
@cv_usk
AI / Software Research Notes AI Agent, LLMOps, MLOps, Software Architecture 投稿は個人の意見です。
加入 May 2026
282 正在关注    431 粉丝
# Practical and Useful Patterns for OpenAI Agent SDK 🌍 Inject what your agent needs with type safety! Local context lets you pass user info, loggers, and data fetchers like dependency injection. 📌 Title: Context management – Local context 🔗 URL: 🧩 Overview The OpenAI Agent SDK's local context feature provides type-safe dependency injection for agents and tools. By passing a Pydantic model or dataclass via the `context` parameter, tool functions can access user information, loggers, and external service clients. The generic type `Agent[UserInfo]` enables compile-time detection of context type mismatches. 🛠 Usage Define a `UserInfo` dataclass with `uid`, `name`, and `is_premium` fields, then use `@tool`-decorated functions that accept `ToolContext[UserInfo]`. For example, `get_recommendations(wrapper: ToolContext[UserInfo], category: str)` accesses user info via `wrapper.context` and returns premium or regular recommendations based on ` A `debug_tool` can access `wrapper.tool_name`, `wrapper.tool_call_id`, and `wrapper.tool_arguments` for debugging. Define the agent with the generic type `Agent[UserInfo]` as `Agent(name="personal_assistant", instructions="Personalize responses for the user", tools=[get_recommendations, debug_tool])`. At runtime, create `UserInfo(uid="u_12345", name="Alice", is_premium=True)` and pass it via `await "Recommend some books", context=user)`. For a more practical setup, bundle dependencies into an `AppContext` dataclass with `user: UserInfo`, `logger: logging.Logger`, `db: DatabaseClient`, and `feature_flags: dict[str, bool]`. In `fetch_order_history(wrapper: ToolContext[AppContext], limit: int = 10)`, access context via `ctx = wrapper.context`, log with ` branch on `ctx.feature_flags.get("new_order_api")`, and query with `ctx.db.get_orders(ctx.user.uid, limit)`. Define the agent as `Agent[AppContext]` with `Agent(name="order_assistant", tools=[fetch_order_history])`. 🏗 Practical Patterns The greatest value of local context is keeping tool functions as pure business logic. Instead of referencing user info or DB clients through global variables, injecting them via context dramatically improves testability — just pass a mock context in tests. `ToolContext`'s `tool_name`, `tool_call_id`, and `tool_arguments` are essential for structured logging. You can trace exactly which tool was called with which arguments, making production debugging straightforward. Using the generic type `Agent[UserInfo]` lets type checkers (mypy, etc.) detect context type mismatches. For example, passing an `AppContext` to an `Agent[UserInfo]` triggers a compile error, preventing runtime failures. Passing feature flags and configuration values through context is also effective. You can control environment-specific behavior through context values without changing code. 💡 Use Cases 👤 Personalization based on premium/free user tiers 📝 Structured logging and tracing with tool_call_id 🧪 Unit testing with mock context injection 🚩 Feature flag-driven tool behavior switching ⚠️ Caveats - Including secrets (API keys, etc.) in context risks leakage during state serialization - Context objects are shared during execution — be careful with mutable state and thread safety - `Agent[T]` generic type checking depends on static analysis tools; it's not enforced at runtime - Putting large objects (bulk data, etc.) in context degrades memory efficiency ✨ Local context enables clean-architecture, testable agents with proper dependency injection! #OpenAIAgentSDK# #AIAgent#
显示更多