Register and share your invite link to earn from video plays and referrals.

Search results for def_quality
def_quality community
One keyword maps to one global community path.
Create community
People
Not Found
Tweets including def_quality
# Useful but Little-Known Features of ADK 2.0 🌍 Do you know the different types of callbacks in ADK 2.0 and when to use each one? ADK 2.0 provides callbacks across three layers: agent lifecycle, LLM calls, and tool execution. The Before/After pattern at each layer lets you flexibly inject validation, guardrails, logging, and more. 📌 Title: Types and Patterns of Callbacks 🔗 URL: 🧩 Overview ADK 2.0 callbacks fall into three categories. Agent lifecycle callbacks (`BeforeAgentCallback` / `AfterAgentCallback`) insert processing before and after agent execution — useful for validation and cleanup. LLM callbacks (`BeforeModelCallback` / `AfterModelCallback`) operate around model calls for request modification and guardrails. Tool callbacks (`BeforeToolCallback` / `AfterToolCallback`) handle validation and result processing around tool execution. 🛠 How to use it Callbacks are specified when defining an agent. In Python, exact parameter names (`callback_context`, `llm_request`, `tool_context`) are required. ```python from adk import Agent async def before_agent(callback_context) -> None: """Validate before agent execution.""" print(f"Agent starting: {callback_context.agent_name}") # Return None to continue, return a value to skip async def before_model(callback_context, llm_request): """Guardrails before model call.""" if contains_sensitive_info(llm_request): return block_response() # returning a value skips the model call return None # continue with normal model call async def after_tool(callback_context, tool_context, tool_response): """Log after tool execution.""" log_tool_usage(tool_context.tool_name, tool_response) return None agent = Agent( name="my_agent", model="gemini-3.5-flash", before_agent_callback=before_agent, before_model_callback=before_model, after_tool_callback=after_tool, ) ``` Before callbacks that return a value skip subsequent processing; returning None continues normal execution. 🏗 Building it into production ・Use `BeforeAgentCallback` for input validation and auth checks to reject bad requests early ・Apply guardrails (PII detection, harmful content filters) in `BeforeModelCallback` ・Validate model output format and policy compliance in `AfterModelCallback` ・Record tool execution results in `AfterToolCallback` for audit trails 💡 Use cases 🛡 Block prompts containing personal information with `BeforeModelCallback` 📝 Record agent execution results to a database with `AfterAgentCallback` ✅ Validate tool call parameters with `BeforeToolCallback` 🔍 Verify JSON format of model output in `AfterModelCallback` and trigger retries ⚠️ Watch out In Python, callback function parameter names must be exact — `callback_context`, `llm_request`, `tool_context`, etc. Mismatched names will cause silent failures. Be careful not to accidentally return a value from Before callbacks, as this skips model calls or tool execution. Also remember that callbacks execute after plugins in the processing order. ✨ Using the right callbacks at the right layer gives you fine-grained control over agent behavior. Combine callbacks across layers to meet your security, quality assurance, and audit requirements. #ADK# #AIAgent#
Show more
# Useful but Little-Known Features of Claude Agent SDK 🌍 Need different agent configurations based on runtime conditions? Factory functions let you dynamically generate agent definitions! Claude Agent SDK supports the factory function pattern to create customized AgentDefinitions on the fly, adapting prompts, models, and tools to runtime context. 📌 Title: Dynamic Agent Definitions (Factory Functions) 🔗 URL: 🧩 Overview By creating factory functions that return `AgentDefinition`, you can dynamically generate agents customized to runtime conditions such as security level, user permissions, or environment. Agents are created at query time, so each request can use different configurations. For example, a strict security review can use the `opus` model while a routine review uses `sonnet`, all from the same factory function. 🛠 How to Use ```python # Python - generate agents based on security level from claude_agent_sdk import query, ClaudeAgentOptions, AgentDefinition def create_security_agent(security_level: str) -> AgentDefinition: is_strict = security_level == "strict" return AgentDefinition( description="Security code reviewer", prompt=f"You are a {'strict' if is_strict else 'balanced'} security reviewer...", tools=["Read", "Grep", "Glob"], model="opus" if is_strict else "sonnet", # Switch model by importance ) # Call factory at query time async for message in query( prompt="Review this PR for security issues", options=ClaudeAgentOptions( allowed_tools=["Read", "Grep", "Glob", "Agent"], agents={ "security-reviewer": create_security_agent("strict") }, ), ): if hasattr(message, "result"): print(message.result) ``` ```typescript // TypeScript function createSecurityAgent(level: "basic" | "strict"): AgentDefinition { const isStrict = level === "strict"; return { description: "Security code reviewer", prompt: `You are a ${isStrict ? "strict" : "balanced"} security reviewer...`, tools: ["Read", "Grep", "Glob"], model: isStrict ? "opus" : "sonnet", }; } for await (const message of query({ prompt: "Review this PR for security issues", options: { allowedTools: ["Read", "Grep", "Glob", "Agent"], agents: { "security-reviewer": createSecurityAgent("strict") } } })) { if ("result" in message) console.log(message.result); } ``` 🏗 Integration into Production Systems - Assign different models and tool sets based on user permission levels or subscription plans - Read conditions from environment variables or config files to generate environment-appropriate agents - Switch `model` based on task importance to optimize the cost-quality tradeoff - Combine multiple factory functions to dynamically compose diverse agent teams 💡 Use Cases 🔐 Use opus for critical security reviews, sonnet for routine reviews 👥 Multi-tenant systems that dynamically adjust available tools based on user permissions 🌐 Generate agents with localized prompts based on region or language settings ⚠️ Caveats - Factory functions are called synchronously at query time, so avoid heavy processing inside them - Generated agents follow the same constraints as regular AgentDefinitions (e.g., subagents cannot spawn subagents) - Since configurations are generated dynamically, log which configuration was used for easier debugging ✨ The factory function pattern lets one codebase serve diverse use cases with tailored agents. Instead of hardcoding conditionals, delegate to factories! #ClaudeAgentSDK# #AIAgent#
Show more
# Useful but Little-Known Features of OpenAI Agent SDK 🌍 Want to manage and version your prompts on the platform instead of hardcoding them? With Prompt Templates, you can reference prompts created on the OpenAI platform from the SDK, injecting variables dynamically. 📌 Title: Prompt Templates 🔗 URL: 🧩 Overview Instead of `instructions`, you can use the `prompt` parameter to reference prompt templates created and managed on the OpenAI platform. For static usage, pass a dict like `{"id": "pmpt_123", "version": "1", "variables": {...}}`. For dynamic usage, pass an async function that returns a prompt dict at runtime, enabling context-dependent variable injection. 🛠 How to use it ```python from agents import Agent, RunContextWrapper # Static template reference agent_static = Agent( name="support", prompt={ "id": "pmpt_abc123", "version": "1", "variables": { "company_name": "Acme Corp", "support_level": "premium", }, }, ) # Dynamic template reference async def dynamic_prompt( context: RunContextWrapper[UserContext], agent: Agent, ) -> dict: user = context.context return { "id": "pmpt_abc123", "version": "2", "variables": { "company_name": "support_level": user.plan, "language": user.language, }, } agent_dynamic = Agent( name="dynamic-support", prompt=dynamic_prompt, ) ``` 🏗 Building it into production ・Manage prompts on the platform for updates and rollbacks without code deployment ・Use version pinning for stable behavior while gradually rolling out new versions ・Inject user-attribute-based variables with dynamic templates ・Share and reuse prompts across teams for quality standardization 💡 Use cases 📝 Prompt version management and staged rollouts 🏢 Cross-organization prompt sharing and standardization 🔄 Prompt updates without code deployment 👤 Dynamic variable injection based on user attributes ⚠️ Watch out `prompt` and `instructions` are mutually exclusive; specifying both causes an error. If the referenced prompt doesn't exist on the platform, you'll also get an error. Verify prompt IDs and versions before deployment, and watch for variable name typos. ✨ With Prompt Templates, move prompt management from "inside the code" to "the platform dashboard." #OpenAIAgentSDK# #AIAgent#
Show more
"Less than 1% of global assets are onchain." The other 99% is still sitting in traditional finance, waiting for infrastructure that can actually handle it. That's what @alignedlayer is building for. 1️⃣ What is Aligned? Aligned is a one-click stack that helps fintechs, institutions, and enterprises build financial products on Ethereum. It brings the infrastructure businesses need to build on Ethereum together through one integration. Basically, teams can use it to launch products like neobanks, stablecoin payment rails, and digital identity systems. 2️⃣ The problem it solves Companies usually cannot build an Ethereum-based product using just one tool. A fintech might need several different providers just to handle the infrastructure behind one product. That means more integrations, higher costs, and more time spent managing different providers. So instead of stitching all of that infrastructure together themselves, a team can use Aligned as the backend and focus more on building the actual product. To me, it sounds like a good quality-of-life solution, in a space where things can get hectic fast. 3️⃣ How the stack works The cool part is that Aligned handles most of the boring backend stuff while making the app feel like something you’re already used to using, like PayPal or Revolut. You log in using Google or Face ID, and an Ethereum wallet is created for you in the background. That is what Wallet-as-a-Service is designed for. Users get a real Ethereum wallet without needing seed phrases or browser extensions. They don't even need to hold ETH in their wallet because it supports gas sponsorship. Aligned is also building Rollup-as-a-Service, which will let businesses run their product on a dedicated rollup with its own rules and infrastructure. I love how they’re making this work like a normal fintech app without reminding you that you’re using crypto in the first place. 4️⃣ What is already live? Aligned’s Proof Aggregation Service has been live in mainnet alpha since January 2026. Instead of verifying every ZK proof separately on Ethereum, it combines multiple proofs into batches, which helps keep verification costs lower as activity grows. So while some of Aligned’s other products are still being built, this part of the stack is already live and working. I’ll def send another update when the rest goes live. 5️⃣ TGE $ALIGN is the native token of the Aligned ecosystem. It is an ERC-20 token on Ethereum with a fixed supply of 10B tokens and an initial circulating supply of approximately 16%. You can check your airdrop eligibility here: Also, make sure to follow @alignedlayer for official updates on the TGE and to see what other products they have in the pipeline. NFA. DYOR.
Show more
# Useful but Little-Known Features of Claude Agent SDK 🌍 Let AI modify your files with confidence -- you can always roll back. File checkpointing automatically tracks changes made by Write/Edit/NotebookEdit and lets you rewind to any point in time. 📌 Title: File Checkpointing and Rollback 🔗 URL: 🧩 Overview File checkpointing tracks file modifications during agent sessions. When you set enable_file_checkpointing=True, the SDK creates backups before any Write, Edit, or NotebookEdit tool modifies a file. Each UserMessage's UUID serves as a checkpoint, and you can call rewind_files() with that UUID to restore files to that point. Created files get deleted, and modified files are restored to their original content. 🛠 How to Use ```python import asyncio from claude_agent_sdk import ( ClaudeSDKClient, ClaudeAgentOptions, UserMessage, ResultMessage, ) async def main(): # Step 1: Enable checkpointing options = ClaudeAgentOptions( enable_file_checkpointing=True, permission_mode="acceptEdits", extra_args={"replay-user-messages": None}, # Required for UUIDs ) checkpoint_id = None session_id = None async with ClaudeSDKClient(options) as client: await client.query("Refactor the authentication module") # Step 2: Capture checkpoint UUID from UserMessage async for message in client.receive_response(): if isinstance(message, UserMessage) and message.uuid and not checkpoint_id: checkpoint_id = message.uuid if isinstance(message, ResultMessage) and not session_id: session_id = message.session_id # Step 3: Resume session and rollback if checkpoint_id and session_id: async with ClaudeSDKClient( ClaudeAgentOptions( enable_file_checkpointing=True, resume=session_id ) ) as client: await client.query("") # Empty prompt to open connection async for message in client.receive_response(): await client.rewind_files(checkpoint_id) break print(f"Rewound to checkpoint: {checkpoint_id}") ``` 🏗 Integration into Production Systems - extra_args={"replay-user-messages": None} is required; without it, UUIDs won't appear in the stream - To rollback, resume the session, send an empty prompt, then call rewind_files() - Persist checkpoint UUIDs and session IDs to enable rollback after process restarts - Combine with permission_mode="acceptEdits" to auto-approve file changes while maintaining rollback safety 💡 Use Cases 🔧 Safe refactoring: try changes and instantly rollback if issues arise 🧪 Experimental code generation: validate AI output and revert if quality is low 📝 Auto-generated documentation: review results and undo unwanted changes ⚠️ Caveats - Changes via Bash commands (echo > file.txt, sed -i, etc.) are NOT tracked - Only file content is tracked; directory creation/move/deletion is not undone - Conversation history is not rolled back -- only files are restored - Checkpoints are tied to the session that created them ✨ Develop fearlessly with "undo-able" AI -- let the agent code with confidence! #ClaudeAgentSDK# #AIAgent#
Show more
# Useful but Little-Known Features of ADK 2.0 🌍 What if your agent could remember conversations from last week and use that context to give better answers today? ADK 2.0's Memory feature provides agents with long-term knowledge that persists across sessions. It stores past conversations and learned information, retrieving them when needed. 📌 Title: Memory 🔗 URL: 🧩 Overview Unlike State, Memory manages long-term knowledge that spans across sessions. Three memory service implementations are available: InMemoryMemoryService for development and testing, VertexAiMemoryBankService for production with semantic search, and VertexAiRagMemoryService for vector-based RAG. Two built-in tools handle retrieval: PreloadMemory (auto-loads at session start) and LoadMemory (loads on demand). For programmatic access, use tool_context.search_memory(). You can also combine multiple memory services through custom tools. 🛠 How to use it Set up a memory service and add memory tools to your agent. ```python from google.adk.memory import InMemoryMemoryService from import PreloadMemory, LoadMemory # Development: in-memory implementation memory_service = InMemoryMemoryService() # Add memory tools to the agent agent = Agent( name="assistant", tools=[PreloadMemory(), LoadMemory()], ... ) # Configure the runner with the memory service runner = Runner( agent=agent, memory_service=memory_service, ... ) ``` To search memory programmatically from within a tool: ```python def my_tool(query: str, tool_context: ToolContext) -> str: results = tool_context.search_memory(query="past conversations") return str(results) ``` For multiple memory sources, create custom tools that integrate them together. 🏗 Building it into production ・Prototype quickly with InMemoryMemoryService, then switch to VertexAI services for production ・Use PreloadMemory to auto-load frequently needed context and improve response quality ・Design appropriate boundaries for what gets stored in memory to prevent data bloat ・Build custom tools to integrate multiple memory sources into a comprehensive knowledge base 💡 Use cases 🧠 Generate personalized responses based on past conversation history 📚 Retain long-term memory of project discussions and decisions 🔍 Automatically retrieve relevant past interactions via semantic search 🤝 Share a knowledge base across multiple agents using memory as a common layer ⚠️ Watch out InMemoryMemoryService loses all data when the process terminates — do not use it in production. VertexAI-based services require GCP setup and configuration. As stored data grows, search latency can be affected, so plan a data management strategy for your memory stores. ✨ Memory gives your agents the ability to carry context across sessions. It's a game-changer for building agents that deliver consistently better long-term user experiences. #ADK# #AIAgent#
Show more
# Useful but Little-Known Features of ADK 2.0 🌍 How do you keep track of user preferences, intermediate results, and shared data across agent conversations? ADK 2.0's State system makes it straightforward. ADK 2.0's State feature is a key-value scratchpad for persisting and sharing data within and across sessions. Different prefixes control the scope of each piece of state. 📌 Title: State Management 🔗 URL: 🧩 Overview State is a key-value data store with four scopes determined by prefixes. No prefix means session scope (valid only within the current session). The user: prefix shares state across multiple sessions for the same user. The app: prefix makes state global across all users and sessions. The temp: prefix creates temporary state that is discarded after the invocation ends. You can reference state values in agent instructions using the {key} syntax, enabling dynamic prompt construction. 🛠 How to use it There are several ways to write state values. ```python # 1. Auto-save agent output with output_key agent = Agent( name="summarizer", output_key="last_summary", ... ) # 2. Explicitly set via EventActions.state_delta from import EventActions actions = EventActions(state_delta={"user:preference": "dark_mode"}) # 3. Set from within tools via ToolContext def my_tool(query: str, tool_context: ToolContext) -> str: tool_context.state["app:global_counter"] = 42 tool_context.state["temp:intermediate"] = "temporary_value" return "done" ``` Reference state in instructions like this: ```python agent = Agent( instruction="User preference is {user:preference}. Previous summary: {last_summary}", ... ) ``` 🏗 Building it into production ・Choose the right scope for each piece of data — use temp: for throwaway intermediate results ・Design user: and app: scoped state carefully, as changes affect multiple sessions ・Always read and write state through CallbackContext or ToolContext to ensure event tracking ・Establish consistent naming conventions for state keys across your team 💡 Use cases 👤 Persist user preferences across sessions with the user: prefix 📊 Track application-wide statistics and counters with app: prefix 🔄 Automatically reference the previous agent output in the next step via output_key 🧹 Store intermediate computation results temporarily with temp: to keep sessions clean ⚠️ Watch out Do not directly modify session.state outside of a context. Bypassing CallbackContext or ToolContext skips event tracking, meaning state changes won't be recorded in the event history. This can break rewind functionality and make debugging significantly harder. ✨ By leveraging State's four scopes, you can flexibly manage agent memory and context. Proper state management is the foundation of high-quality agent experiences. #ADK# #AIAgent#
Show more
# 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#
Show more
Def Leppard Announce Extensive 2027 North American Tour With Goo Goo Dolls, The Struts
DEF’s CEO & CLO @amandatums will take the stage on Monday at @SolanaInstitute’s Washington x Wall Street Summit with security experts: @claudijd @_mwc @NotDeGhost. They’ll unpack what “onchain security” means, how it’s unique, great work being done today, and what’s to come.
Show more