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

Search results for ADK
ADK community
One keyword maps to one global community path.
Create community
People
Not Found
Tweets including ADK
Trace Adkins details being shot by his ex-wife during heated argument: ‘Totally uncalled for’
# Useful but Little-Known Features of ADK 2.0 🌍 Sending the same system prompt and tool definitions to the LLM on every call wastes both money and time. What if the SDK could cache that for you? ADK 2.0's ContextCacheConfig caches repeated context data sent to the LLM, reducing both API costs and response latency. Available with Gemini 2.0+, Python v1.15.0+, and Java v0.1.0+. 📌 Title: Context Cache (ContextCacheConfig) 🔗 URL: 🧩 Overview ContextCacheConfig reduces token consumption by caching context sent to the LLM — system prompts, tool definitions, fixed portions of conversation history, and more. It has three key parameters: min_tokens sets the minimum token threshold for caching to activate (default 0), ttl_seconds controls cache lifetime (default 1800 seconds / 30 minutes), and cache_intervals limits maximum cache reuse count (default 10). Configure it on the App object and caching is applied automatically. 🛠 How to use it Create a ContextCacheConfig and set it on the App. ```python from import App from google.adk.context import ContextCacheConfig cache_config = ContextCacheConfig( min_tokens=1000, # Cache only when context >= 1000 tokens ttl_seconds=3600, # Keep cache for 1 hour cache_intervals=20, # Reuse up to 20 times ) app = App( agent=my_agent, context_cache_config=cache_config, ) ``` Setting min_tokens appropriately ensures that small contexts are sent normally while large contexts benefit from caching. 🏗 Building it into production ・Agents with large system prompts or many tool definitions benefit the most from caching ・Tune ttl_seconds to match your workload pattern (short conversations → shorter TTL, long ones → longer TTL) ・Adjust cache_intervals based on request frequency to balance freshness and cost savings ・Monitor cost reduction metrics and continuously optimize parameters 💡 Use cases 💰 Cut API costs for agents with large, stable system prompts ⚡ Reduce response latency by skipping repeated tool definition transmission 🔁 Optimize token consumption for high-frequency chatbot interactions 📋 Efficiently handle fixed context (rules, guidelines, policies) that rarely changes ⚠️ Watch out This feature requires Gemini 2.0 or later. Context changes won't take effect while a cache is active, so set a shorter ttl_seconds if you frequently update system prompts. When cache_intervals is exceeded, a new cache is created, which can cause cost optimization effects to fluctuate. ✨ Context caching delivers significant cost and performance improvements, especially in scenarios with large, frequently-accessed context. It's a quick win for production deployments. #ADK# #AIAgent#
Show more
# Practical and Useful Patterns with ADK ✋ "Are you sure you want to send this email?" — ADK's Action Confirmations add pre-execution user approval for irreversible operations, building safer agents. 📌 Title: Action Confirmations — Pre-Execution Approval for Irreversible Operations 🔗 URL: 🧩 Overview ADK's Action Confirmations require explicit user approval before executing hard-to-reverse operations like email sending, data deletion, and payment processing. The agent asks "Should I proceed?" and only executes upon user approval. This maintains human control at critical decision points while keeping agents autonomous for routine tasks. 🛠 Usage Defining tools with confirmation requirements. To define tools with confirmation, import `Agent` and `ToolContext` from `google.adk`. In `send_email(to: str, subject: str, body: str, tool_context: ToolContext)`, call `tool_context.actions.request_confirmation(message=...)` before the actual send, displaying a preview with recipient, subject, and body. The email is only sent if the user approves. Similarly, `delete_records(table: str, condition: str, tool_context: ToolContext)` counts records to be deleted first, then displays the count in a confirmation message for user approval. Pass both tools to an `Agent` with `name="admin_assistant"` and `model="gemini-2.5-flash"` via the `tools` parameter. 🏗 Practical Patterns **When to Require Confirmation**: Add confirmation for these categories: - External sends (email, messages, API calls) - Data modification or deletion - Operations that incur charges - Permission or access control changes For payment processing, define `process_payment(amount: float, currency: str, recipient: str, tool_context: ToolContext)`. This function calls `tool_context.actions.request_confirmation(message=...)` with the recipient, currency, and amount details. Only after user approval does it execute `payment_gateway.charge(amount=..., currency=..., recipient=...)` to process the transaction. **Confirmation Message Design**: Include the target, scope of impact, and irreversibility in confirmation messages. Provide exactly the information users need to make an informed decision. **Staged Confirmations**: For multi-step operations, decide whether to confirm at each step or summarize at the final step. Balance thoroughness with user experience. 💡 Use Cases 📧 Email and message send confirmation 🗑️ Database record deletion approval 💳 Payment and transfer execution confirmation 🔐 Permission and access control change approval ⚠️ Caveats - Too many confirmations degrade user experience. Limit confirmations to truly irreversible operations. - Insufficient confirmation messages prevent users from making informed decisions. Be specific about the operation's impact. - Confirmations become bottlenecks in batch processing and automation pipelines. Consider skippable confirmations for automated scenarios. ✨ Properly configured Action Confirmations balance agent autonomy with human safety oversight. The key is confirming only "can't-undo" operations! #ADK# #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
# Practical and Useful Patterns with ADK 🚀 Parallel tool execution, response size reduction, latency and token cost optimization — maximize production throughput with ADK's Tool Performance guide. 📌 Title: Tool Performance — Optimizing Tool Execution for Production 🔗 URL: 🧩 Overview ADK provides multiple approaches for optimizing tool performance: parallel execution of read-only tools, response size reduction for token cost optimization, and latency reduction best practices. These optimizations are essential for achieving high throughput in production environments. 🛠 Usage Examples of parallel execution and response optimization. First, define multiple read-only tools: `get_user_profile(user_id: str)`, `get_user_orders(user_id: str)`, and `get_user_preferences(user_id: str)` are side-effect-free functions that ADK can safely execute in parallel. Next, design a response-size-optimized tool like `search_products(query: str, limit: int = 5)` that returns only essential fields (`id`, `name`, `price`) while omitting image URLs, full descriptions, and metadata. Finally, create an `Agent` with `name="customer_service"` and `model="gemini-2.5-flash"`, passing all four functions in the `tools` list. 🏗 Practical Patterns **Parallel Execution Criteria**: Tools with no side effects and no mutual dependencies are safe for parallel execution. The LLM can invoke multiple tools simultaneously, and ADK executes them in parallel. Data retrieval tools (GET-equivalent) are great candidates. For parallel-friendly design, define independent tools like `get_weather(city: str)`, `get_news(topic: str)`, and `get_stock_price(symbol: str)`. Each is a read-only function returning a simple dict with its respective data (weather conditions, news articles, stock prices). When the LLM invokes all three simultaneously, ADK automatically runs them in parallel. **Response Size Optimization**: Tool return values consume LLM context window tokens. Removing unnecessary fields, summarizing data, and implementing pagination can dramatically reduce token costs. **Latency Optimization Checklist**: 1. Cache cacheable results 2. Set timeouts on external API calls 3. Avoid returning unnecessarily large data 4. Split into multiple small tools to encourage parallel execution 💡 Use Cases 📊 Parallel fetching from multiple data sources for dashboards 🔍 Field filtering in search results for token savings ⚡ Parallel API calls across microservices 💰 Token cost optimization in high-volume request environments ⚠️ Caveats - Parallel execution of tools with side effects (writes, deletes) can cause race conditions. Sequential execution is recommended for write operations. - Over-reducing responses may leave the LLM without sufficient information, degrading answer quality. Ensure essential information is always included. - Timeouts that are too short may interrupt legitimate responses. Set appropriate timeout values. ✨ Small optimizations compound into significant performance differences in production. Start by reviewing your response sizes! #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 with ADK ⚡ Turn Python functions into tools, wrap agents as tools, and run long tasks without blocking — ADK's Function Tools maximize flexibility in tool definitions. 📌 Title: Function Tools — Functions, Agents, and Async Tasks as Tools 🔗 URL: 🧩 Overview ADK's Function Tools let you use Python/TypeScript functions directly as agent tools. AgentTool wraps an entire agent as a tool accessible to other agents. Long Running Function Tools handle time-consuming tasks like video encoding and batch jobs without blocking the agent's execution flow. 🛠 Usage Basic function tool definitions and AgentTool usage. Import `Agent` and `AgentTool` from `google.adk`. Define a simple function tool `calculate_price` that takes `base_price` (float), `quantity` (int), and `discount_percent` (float, default 0), computes the total with the discount applied, and returns a dict with `total` and `currency`. For wrapping an agent as a tool, create an `analysis_agent` with `name="data_analyst"` and `tools=[query_database]`. Then define `main_agent` with `tools=[calculate_price, AgentTool(agent=analysis_agent)]`, allowing the main agent to call both the pricing function and the data analysis agent as tools. Using Long Running Function Tools. Import `LongRunningFunctionTool` from `google.adk`. Define an async function `encode_video` that takes `video_url` (str) and `format` (str, default "mp4"), starts an encoding job via `start_encoding_job`, and returns the job ID with a processing status. Wrap it with `LongRunningFunctionTool(func=encode_video)` to create `video_tool`, then pass it to an `Agent`'s `tools` list so the agent can trigger long-running tasks without blocking. 🏗 Practical Patterns **Modularization with AgentTool**: Encapsulate complex logic as specialized agents and expose them via AgentTool. This keeps the main agent's instructions simple while each specialist agent maintains its own tools and prompts -- achieving clean separation of concerns. Define a `summarizer` agent (for 3-line summaries) and a `translator` agent (for Japanese translation) as separate `Agent` instances. Then create a `content_manager` agent with `tools=[AgentTool(agent=summarizer), AgentTool(agent=translator)]`, allowing the main agent to invoke these specialists as tools for content management tasks. **When to Use Long Running Tools**: Ideal for batch processing, external API polling, file conversion — anything taking seconds to minutes. The agent receives a job ID and can proceed with other tasks in parallel. **Type Annotations Matter**: Clear parameter types and return types help the LLM call tools accurately. Docstrings serve as tool descriptions, so keep them concise and clear. 💡 Use Cases 🧮 Calculation and conversion functions as tools (pricing, unit conversion) 🤖 Reusable specialist agents via AgentTool 🎬 Async video encoding and image processing 📊 Non-blocking batch data processing ⚠️ Caveats - Function docstrings become tool descriptions. Write LLM-friendly descriptions — missing docstrings make tool purposes unclear. - Agents called via AgentTool run in a separate session from the parent. Be careful about state sharing. - Long Running Function Tools require a separate completion notification mechanism. Consider polling or webhook-based notifications. ✨ Function Tools let you integrate existing code assets directly into agents, and AgentTool enables seamless agent reuse. A massive boost to development productivity! #ADK# #AIAgent#
Show more
# Useful but Little-Known Features of ADK 2.0 🌍 What if you could safely cancel a running agent mid-execution while preserving everything it has already accomplished? ADK 2.0's cancellation feature uses the AbortController/AbortSignal pattern to gracefully interrupt agent execution. The cancel signal propagates through Runner, LlmAgent, Models, and Tools, while committed events are preserved. 📌 Title: Cancelling Agent Execution 🔗 URL: 🧩 Overview Agent cancellation follows the AbortController/AbortSignal pattern. When a signal is issued from an AbortController, it propagates through the stack: Runner → LlmAgent → Models → Tools. Crucially, events that have already been committed are preserved, and the process completes gracefully without throwing exceptions. AbortSignal.timeout() enables automatic timeout-based cancellation, and AbortSignal.any() lets you combine multiple signals. 🛠 How to use it Create an AbortController and pass its signal to the Runner. ```python from adk import App, AbortController, AbortSignal app = App(agent=my_agent) # Manual cancellation controller = AbortController() task = "long task", signal=controller.signal) # Cancel when needed controller.abort() # Timeout-based auto-cancel (2 seconds) signal = AbortSignal.timeout(2000) result = await "time-limited task", signal=signal) # Combining multiple signals combined = AbortSignal.any([ AbortSignal.timeout(5000), user_cancel_signal ]) result = await "task", signal=combined) ``` 🏗 Building it into production ・Wire AbortController to user actions (cancel buttons) to enable UI-driven cancellation ・Use AbortSignal.timeout() to cap maximum execution time for API calls and prevent resource waste ・Combine user cancellation and timeout signals with AbortSignal.any() ・Design workflows to return partial results from committed events after cancellation 💡 Use cases ⏱ Set timeouts on LLM calls to auto-cancel when responses are slow 🖱 Instantly interrupt agent execution when a user clicks a cancel button in the UI 🔀 Run multiple agents in parallel and cancel all but the first to complete 💰 Cut off LLM calls when a cost budget is reached ⚠️ Watch out Cancellation completes gracefully, meaning the agent does not stop the instant abort() is called. There may be a slight delay while the current operation (LLM inference, tool execution) finishes. Since committed events are preserved, design your workflows with cancellation points in mind to avoid inconsistent intermediate states. Implementing signal-aware early returns inside tools is also an effective practice. ✨ The cancellation feature gives you safe control over the agent execution lifecycle. Combined with timeouts, it dramatically improves predictability in production environments. #ADK# #AIAgent#
Show more