Skip to content
Closed
Show file tree
Hide file tree
Changes from 30 commits
Commits
Show all changes
154 commits
Select commit Hold shift + click to select a range
fd010d0
feat: Add enhanced environment validation with fallbacks
Adebesin-Cell Oct 14, 2025
60326ef
fix: merge conflicts
Adebesin-Cell Oct 14, 2025
1c97dd6
style: Improve error handling and logging efficiency
Adebesin-Cell Oct 14, 2025
bfefd8c
refactor: Improve error handling and messages in AgentLoader
Adebesin-Cell Oct 14, 2025
2f88506
refactor: Remove redundant environment validation code
Adebesin-Cell Oct 14, 2025
6537f47
docs: Remove ENVIRONMENT_VARIABLES.md file
Adebesin-Cell Oct 14, 2025
4e7e9e9
feat: Add environment variable validation with clear error messages
Adebesin-Cell Oct 14, 2025
65a0493
refactor: Improve error handling in agent loading
Adebesin-Cell Oct 14, 2025
98b4abe
Merge branch 'main' of https://github.com/IQAIcom/adk-ts into fix/env…
Adebesin-Cell Oct 15, 2025
15af11b
Merge branch 'main' of https://github.com/IQAIcom/adk-ts into fix/env…
Adebesin-Cell Oct 20, 2025
c0016b6
feat: Add agent resolver with cache cleanup utilities
Adebesin-Cell Oct 20, 2025
6cddbb7
refactor: Improve error handling in AgentLoader
Adebesin-Cell Oct 20, 2025
df8392b
style: Remove unnecessary import statement
Adebesin-Cell Oct 20, 2025
acba09e
fix: merge conflicts
Adebesin-Cell Oct 21, 2025
0731091
feat: Add global exception filter for pretty error formatting
Adebesin-Cell Oct 21, 2025
099c473
fix: merge conflicts
Adebesin-Cell Oct 22, 2025
ad2544b
fix: multiple cache file creation
Adebesin-Cell Oct 22, 2025
74223fc
fix: error handling in adk-cli
Adebesin-Cell Oct 22, 2025
d874b7c
Merge branch 'main' into fix/env-error
Royal-lobster Oct 23, 2025
f8584a7
fix: merge conflicts
Adebesin-Cell Oct 24, 2025
bbc2c75
feat: Add ContextCacheConfig class for context caching
Adebesin-Cell Nov 7, 2025
103e6a2
docs: Remove unnecessary adk.code-workspace file
Adebesin-Cell Nov 7, 2025
b4908a5
Merge branch 'feat/add-tracing' of https://github.com/IQAIcom/adk-ts …
Adebesin-Cell Nov 7, 2025
582547a
Merge branch 'feat/add-tracing' of https://github.com/IQAIcom/adk-ts …
Adebesin-Cell Nov 10, 2025
cef481a
feat: Add context caching for Gemini models
Adebesin-Cell Nov 10, 2025
877ae0f
refactor: Improve cache handling in GeminiContextCacheManager
Adebesin-Cell Nov 10, 2025
0185839
refactor: Simplify cache contents slicing logic
Adebesin-Cell Nov 10, 2025
e2de24a
Update packages/adk/src/agents/invocation-context.ts
Adebesin-Cell Nov 10, 2025
0263fc7
Update packages/adk/src/models/gemini-context-cache-manager.ts
Adebesin-Cell Nov 10, 2025
adad054
fix: Add error handling for missing model name
Adebesin-Cell Nov 10, 2025
8217ec7
Merge branch 'feat/support-caching' of https://github.com/IQAIcom/adk…
Adebesin-Cell Nov 10, 2025
6d35321
style: Remove unnecessary commented code
Adebesin-Cell Nov 10, 2025
4de123d
style: Improve code readability with type annotations
Adebesin-Cell Nov 10, 2025
b043645
Update packages/adk/src/models/gemini-context-cache-manager.ts
Adebesin-Cell Nov 10, 2025
37897bc
refactor: Improve data canonicalization in GeminiContextCacheManager
Adebesin-Cell Nov 10, 2025
d300fb9
Merge branch 'feat/support-caching' of https://github.com/IQAIcom/adk…
Adebesin-Cell Nov 10, 2025
f930d2a
style: Update variable names and hash length slicing functionality
Adebesin-Cell Nov 10, 2025
12aae2a
refactor: Update GeminiContextCacheManager constructor arguments
Adebesin-Cell Nov 10, 2025
0492b66
Update packages/adk/src/models/gemini-context-cache-manager.ts
Adebesin-Cell Nov 10, 2025
8a1554c
feat: Add method to configure context caching in AgentBuilder
Adebesin-Cell Nov 10, 2025
3998fe0
feat: Add context caching feature for Gemini models
Adebesin-Cell Nov 10, 2025
2d5b4bd
Update packages/adk/src/models/gemini-context-cache-manager.ts
Adebesin-Cell Nov 10, 2025
82a923a
feat: Update context caching model version to 2.5
Adebesin-Cell Nov 11, 2025
31e9fa9
Merge branch 'feat/support-caching' of https://github.com/IQAIcom/adk…
Adebesin-Cell Nov 11, 2025
f89c1d2
Merge branch 'feat/add-tracing' of https://github.com/IQAIcom/adk-ts …
Adebesin-Cell Nov 11, 2025
a686c24
refactor: Remove redundant contextCacheConfig assignment
Adebesin-Cell Nov 12, 2025
8a32059
Update packages/adk/src/models/gemini-context-cache-manager.ts
Adebesin-Cell Nov 12, 2025
853b83f
chore: Add constants and deprecate in-memory service
Adebesin-Cell Nov 12, 2025
5e08160
refactor: Update cache management logic for Gemini context
Adebesin-Cell Nov 12, 2025
04fc17f
feat: Add tools to createCacheConfig if available
Adebesin-Cell Nov 12, 2025
b18fd5c
Update packages/adk/src/runners.ts
Adebesin-Cell Nov 12, 2025
7383543
feat: Add method to extract cache metadata from session history
Adebesin-Cell Nov 12, 2025
98bdda2
Merge branch 'feat/support-caching' of https://github.com/IQAIcom/adk…
Adebesin-Cell Nov 12, 2025
7131b37
refactor: Refactor models structure for clarity
Adebesin-Cell Nov 12, 2025
262842b
feat: Add UsageMetadata import and typecasting
Adebesin-Cell Nov 12, 2025
cc8d291
Update packages/adk/src/models/gemini-context-cache-manager.ts
Adebesin-Cell Nov 12, 2025
51f0db9
docs: Update context caching configuration settings
Adebesin-Cell Nov 12, 2025
a22d4b3
Merge branch 'feat/support-caching' of https://github.com/IQAIcom/adk…
Adebesin-Cell Nov 12, 2025
c8316b4
refactor: Remove unused constant variables in GeminiContextCacheManager
Adebesin-Cell Nov 12, 2025
ecf5d69
Merge branch 'feat/add-tracing' into feat/support-caching
Adebesin-Cell Nov 13, 2025
fe10adc
feat: Add context caching for Google models
Adebesin-Cell Nov 13, 2025
459ef07
chore(models): Update import order in ai-sdk file
Adebesin-Cell Nov 13, 2025
e5aeacc
Merge branch 'feat/support-caching' of https://github.com/IQAIcom/adk…
Adebesin-Cell Nov 13, 2025
dc6b51e
refactor: Remove unused code related to cache management
Adebesin-Cell Nov 13, 2025
f4120f9
fix: Fix typo in context cache intervals value
Adebesin-Cell Nov 17, 2025
5e1c54e
Merge branch 'feat/add-tracing' into feat/support-caching
Adebesin-Cell Nov 17, 2025
0eb6ffc
Refine documentation for model integration options and improve clarit…
Timonwa Nov 18, 2025
f64b61b
Merge branch 'feat/add-tracing' of https://github.com/IQAIcom/adk-ts …
Adebesin-Cell Nov 18, 2025
d7fc031
style: Improve context caching documentation message
Adebesin-Cell Nov 18, 2025
0bb3f9e
Merge branch 'feat/support-caching' of https://github.com/IQAIcom/adk…
Adebesin-Cell Nov 18, 2025
9bf55d0
Enhance documentation on artifact deletion and cleanup strategies. Ad…
Pelumi-Aderinto Nov 19, 2025
40de7ea
Refactor artifact cleanup service documentation. Updated the `Artifac…
Pelumi-Aderinto Nov 19, 2025
36aa62b
Refactor `ArtifactCleanupService` documentation. Updated import state…
Pelumi-Aderinto Nov 19, 2025
80baccd
Refactor artifact cleanup functionality. Simplified the `cleanupTempo…
Pelumi-Aderinto Nov 19, 2025
95a1edd
docs: fixed errors in code snippets and rearranged the functions
Timonwa Nov 19, 2025
64c8919
docs: update workflow agents documentation for clarity and consistency
Timonwa Nov 19, 2025
193a464
docs: update session links to point to the correct session documentation
Timonwa Nov 19, 2025
a131c82
Update artifact cleanup documentation. Renamed section to "Artifact C…
Pelumi-Aderinto Nov 20, 2025
8aef807
Enhance artifact cleanup documentation. Renamed section to "Artifact …
Pelumi-Aderinto Nov 20, 2025
e56583a
Add listing versions section to artifact documentation. Introduced th…
Pelumi-Aderinto Nov 20, 2025
4459cbc
fix: conflicts
Adebesin-Cell Nov 20, 2025
5e2ab7a
docs: enhance workflow and sequential agents documentation with clear…
Timonwa Nov 20, 2025
6cc723c
docs: remove outdated quick start example for workflow agents
Timonwa Nov 20, 2025
2945e29
docs: update sequential agents example for clarity and structure
Timonwa Nov 20, 2025
b6c5bdf
docs: refine sequential agents example for clarity and consistency
Timonwa Nov 20, 2025
d3f6ace
docs: update parallel agents example for clarity and detail
Timonwa Nov 20, 2025
c5ac16d
docs: forgot to update quick start examples intro for parallel and se…
Timonwa Nov 20, 2025
ec929ef
docs: update quick start example for research synthesis agent with im…
Timonwa Nov 20, 2025
185e20b
docs: enhance code comments for clarity in LangGraph and Loop agents …
Timonwa Nov 20, 2025
0b0ac77
docs: enhance customer support workflow example with detailed agent d…
Timonwa Nov 21, 2025
c8925ef
docs: refine custom agents documentation for clarity and detail, enha…
Timonwa Nov 21, 2025
bef43f0
docs: enhance multi-agent systems documentation with detailed agent d…
Timonwa Nov 21, 2025
abf89c0
docs: load environment variables from .env file in agent builder and …
Timonwa Nov 21, 2025
e29ca30
docs: enhance LLM agents documentation with improved clarity, structu…
Timonwa Nov 21, 2025
bb9699c
docs: refine LangGraph agents documentation with improved examples an…
Timonwa Nov 21, 2025
e703484
Merge remote-tracking branch 'origin/main' into check-agents-section-…
Timonwa Nov 21, 2025
6dd948a
Merge branch 'feat/add-tracing' into feat/support-caching
Adebesin-Cell Nov 21, 2025
47ab1a4
refactor: Simplify message fetching logic and attachments handling
Adebesin-Cell Nov 21, 2025
9b5fde2
setup
MarvelNwachukwu Nov 21, 2025
7aa07a2
docs: update agent builder examples to include dotenv configuration a…
Timonwa Nov 24, 2025
39f9de6
docs: update llm-agents documentation to correct appName type from Ba…
Timonwa Nov 24, 2025
2953826
docs: update dotenv import syntax and configuration usage in agent ex…
Timonwa Nov 24, 2025
e828944
docs: fix typo in import statement for LoopAgent in multi-agents example
Timonwa Nov 24, 2025
d08c933
Update apps/adk-web/hooks/use-agent.ts
Adebesin-Cell Nov 25, 2025
9f1cf2f
refactor: Simplify message transformation and add type guards
Adebesin-Cell Nov 25, 2025
95dc71a
style: Simplify mapping function parameters in use-agent hook
Adebesin-Cell Nov 25, 2025
c340b7c
Merge branch 'main' of https://github.com/IQAIcom/adk-ts into fix/env…
Adebesin-Cell Nov 25, 2025
a11e821
refactor: Simplify code by removing unnecessary type annotations
Adebesin-Cell Nov 25, 2025
fc8e655
Merge pull request #391 from IQAIcom/fix/env-error
Adebesin-Cell Nov 26, 2025
18b8a64
feat: Add step to install dependencies
Adebesin-Cell Nov 26, 2025
94d05b7
Merge branch 'main' into fix/agent-context
Adebesin-Cell Nov 26, 2025
515c53a
Merge pull request #393 from IQAIcom/check-agents-section-code-snippets
Timonwa Nov 26, 2025
d952803
Merge branch 'main' into fix/agent-context
Adebesin-Cell Nov 26, 2025
4b9f016
Merge pull request #394 from IQAIcom/fix/agent-context
Adebesin-Cell Nov 26, 2025
173b8cf
Version Packages
github-actions[bot] Nov 26, 2025
1de9180
Merge pull request #396 from IQAIcom/changeset-release/main
Adebesin-Cell Nov 26, 2025
7d03483
feat: Add typescript dependency
Adebesin-Cell Nov 26, 2025
9b39d9c
style: remove unused code in package.json and client.ts
Adebesin-Cell Nov 26, 2025
51546dd
fix: Update version of @modelcontextprotocol/sdk to 1.11.1
Adebesin-Cell Nov 26, 2025
3aca356
feat: Add prompts capability
Adebesin-Cell Nov 26, 2025
d7acef6
fix: Update @modelcontextprotocol/sdk to version 1.17.5
Adebesin-Cell Nov 27, 2025
6c3b921
fix: remove invalid params
Adebesin-Cell Nov 28, 2025
8d5f928
refactor: Remove unused properties in McpClientService
Adebesin-Cell Nov 28, 2025
cec1eaa
Merge pull request #389 from IQAIcom/feature/artifact-docs
Pelumi-Aderinto Nov 28, 2025
a98adac
fix: mcp type errors
Adebesin-Cell Dec 1, 2025
c642258
fix: add lock
Adebesin-Cell Dec 1, 2025
b938be4
fix: resolve type errors with Model Context Protocol versioning
Adebesin-Cell Dec 1, 2025
d8049ec
Update packages/adk/src/tools/mcp/sampling-handler.ts
Adebesin-Cell Dec 1, 2025
80614a4
refactor: Improve handling of mcpContent data types
Adebesin-Cell Dec 1, 2025
3afe3d9
Merge branch 'fix/release' of https://github.com/IQAIcom/adk-ts into …
Adebesin-Cell Dec 1, 2025
40b3e7a
refactor: Improve data validation and logging in MCP content conversion
Adebesin-Cell Dec 1, 2025
d1c1e19
top three projects image
MarvelNwachukwu Dec 1, 2025
99b42ae
update navbar, showing docs and showcase
MarvelNwachukwu Dec 1, 2025
4cf5063
feat: add community project showcase with dedicated project cards and…
MarvelNwachukwu Dec 1, 2025
fc78eed
fix project card hydration error and add project submission instructi…
MarvelNwachukwu Dec 2, 2025
e83927e
changed layout
MarvelNwachukwu Dec 2, 2025
837928c
showcase discussion
MarvelNwachukwu Dec 2, 2025
f97191c
renamed section and deleted some projects
MarvelNwachukwu Dec 2, 2025
44fda9d
no referrer
MarvelNwachukwu Dec 2, 2025
71e37fb
refactor: extract project data from `page.tsx` into a new `_schema.ts…
MarvelNwachukwu Dec 2, 2025
d1ef3eb
add labels
MarvelNwachukwu Dec 2, 2025
21ace7b
lazy loading
MarvelNwachukwu Dec 2, 2025
4c9c5a9
refactor: Update project data schema to use title, description, and t…
MarvelNwachukwu Dec 2, 2025
7809647
Merge pull request #403 from IQAIcom/adk-showcase
MarvelNwachukwu Dec 2, 2025
45645aa
Merge branch 'main' into fix/release
Adebesin-Cell Dec 2, 2025
c97621a
Merge pull request #402 from IQAIcom/fix/release
Adebesin-Cell Dec 2, 2025
f118046
Version Packages
github-actions[bot] Dec 2, 2025
f4fea2d
Merge pull request #405 from IQAIcom/changeset-release/main
Adebesin-Cell Dec 2, 2025
6a3f485
chore: sync ADK versions across examples and starters
actions-user Dec 2, 2025
8c1bef2
fix: merge conflicts
Adebesin-Cell Dec 3, 2025
1af6dad
Merge branch 'feat/support-caching' of https://github.com/IQAIcom/adk…
Adebesin-Cell Dec 3, 2025
d7d0528
refactor: Improve caching logic for AI SDK
Adebesin-Cell Dec 3, 2025
1e38a2a
chore: update
Adebesin-Cell Dec 3, 2025
111206b
refactor: Improve code readability with type assertions
Adebesin-Cell Dec 3, 2025
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
35 changes: 35 additions & 0 deletions apps/docs/content/docs/framework/context/context-caching.mdx
Original file line number Diff line number Diff line change
@@ -0,0 +1,35 @@
---
title: Context caching with Gemini
description: This document explains how to configure and use the context caching feature.
---

When working with agents to complete tasks, you may want to reuse extended instructions or large sets of data across multiple agent requests to a generative AI model. Resending this data for each agent request is slow, inefficient, and can be expensive. Using context caching features in generative AI models can significantly speed up responses and lower the number of tokens sent to the model for each request.

The ADK Context Caching feature allows you to cache request data with generative AI models that support it, including Gemini 2.0 and higher models. This document explains how to configure and use this feature.


## Configure context caching

You configure the context caching feature when creating your agent by passing a `contextCacheConfig` object directly to your agent. For example:

```typescript
const agent = new LlmAgent({
model: "gemini-2.5-flash", // Configure an agent using a model that supports context caching
// ... other agent properties
contextCacheConfig: {
cacheIntervals: 10,
ttlSeconds: 1800,
minTokens: 1000,
},
});
```

## Configuration settings

The `contextCacheConfig` object has the following settings that control how caching works for your agent:

* **minTokens** (`number`): The minimum number of tokens required in a request to enable caching. This avoids caching very small requests where the performance benefit is negligible. **Default:** `0`.

* **ttlSeconds** (`number`): The time-to-live (TTL) for the cache in seconds. Determines how long cached content is stored before it is refreshed. **Default:** `1800` (30 minutes).

* **cacheIntervals** (`number`): The maximum number of times the same cached content can be used before it expires. Allows control over how frequently the cache is updated, even if the TTL has not expired. **Default:** `10`.
3 changes: 2 additions & 1 deletion apps/docs/content/docs/framework/context/meta.json
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,8 @@
"callback-context",
"tool-context",
"invocation-context",
"context-patterns"
"context-patterns",
"context-caching"
],
"icon": "Brain"
}
34 changes: 34 additions & 0 deletions packages/adk/src/agents/agent-builder.ts
Original file line number Diff line number Diff line change
Expand Up @@ -20,6 +20,10 @@ import type {
BaseAgent,
BeforeAgentCallback,
} from "./base-agent.js";
import {
ContextCacheConfig,
type ContextCacheConfigProps,
} from "./context-cache-config.js";
import { LangGraphAgent, type LangGraphNode } from "./lang-graph-agent.js";
import type {
AfterModelCallback,
Expand Down Expand Up @@ -155,6 +159,7 @@ interface RunnerConfig {
memoryService?: BaseMemoryService;
artifactService?: BaseArtifactService;
eventsCompactionConfig?: EventsCompactionConfig;
contextCacheConfig?: ContextCacheConfig;
}

/**
Expand Down Expand Up @@ -208,6 +213,7 @@ export class AgentBuilder<TOut = string, TMulti extends boolean = false> {
private memoryService?: BaseMemoryService;
private artifactService?: BaseArtifactService;
private eventsCompactionConfig?: EventsCompactionConfig;
private cacheConfig?: ContextCacheConfig;
private agentType: AgentType = "llm";
private existingSession?: Session;
private existingAgent?: BaseAgent; // If provided, reuse directly
Expand Down Expand Up @@ -648,6 +654,33 @@ export class AgentBuilder<TOut = string, TMulti extends boolean = false> {
return this;
}

/**
* Configure context caching for Gemini models
* @param config Cache configuration options (cacheIntervals, ttlSeconds, minTokens)
* @returns This builder instance for chaining
* @example
* ```typescript
* const { runner } = await AgentBuilder
* .create("assistant")
* .withModel("gemini-2.5-flash")
* .withCacheConfig({
* cacheIntervals: 10, // Reuse cache for 10 invocations
* ttlSeconds: 1800, // Cache expires after 30 minutes
* minTokens: 1000, // Only cache if request has 1000+ tokens
* })
* .build();
* ```
*/
withCacheConfig(
config: Partial<ContextCacheConfigProps> | ContextCacheConfig,
): this {
this.cacheConfig =
config instanceof ContextCacheConfig
? config
: new ContextCacheConfig(config);
return this;
}

/**
* Configure runtime behavior for runs
*/
Expand Down Expand Up @@ -724,6 +757,7 @@ export class AgentBuilder<TOut = string, TMulti extends boolean = false> {
memoryService: this.memoryService,
artifactService: this.artifactService,
eventsCompactionConfig: this.eventsCompactionConfig,
contextCacheConfig: this.cacheConfig,
};

const baseRunner = new Runner(runnerConfig);
Expand Down
5 changes: 5 additions & 0 deletions packages/adk/src/agents/base-agent.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@ import type { Content } from "@google/genai";
import { Event } from "../events/event";
import { telemetryService } from "../telemetry";
import { CallbackContext } from "./callback-context";
import { ContextCacheConfig } from "./context-cache-config";
import type { InvocationContext } from "./invocation-context";

/**
Expand Down Expand Up @@ -83,6 +84,8 @@ export abstract class BaseAgent {
*/
afterAgentCallback?: AfterAgentCallback;

contextCacheConfig?: ContextCacheConfig;

/**
* Constructor for BaseAgent
*/
Expand All @@ -92,12 +95,14 @@ export abstract class BaseAgent {
subAgents?: BaseAgent[];
beforeAgentCallback?: BeforeAgentCallback;
afterAgentCallback?: AfterAgentCallback;
contextCacheConfig?: ContextCacheConfig;
}) {
this.name = config.name;
this.description = config.description || "";
this.subAgents = config.subAgents || [];
this.beforeAgentCallback = config.beforeAgentCallback;
this.afterAgentCallback = config.afterAgentCallback;
this.contextCacheConfig = config.contextCacheConfig;

// Validate agent name
this.validateName(this.name);
Expand Down
118 changes: 118 additions & 0 deletions packages/adk/src/agents/context-cache-config.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,118 @@
import { z } from "zod";

/**
* Zod schema defining validation rules for ContextCacheConfig.
*/
export const contextCacheConfigSchema = z.object({
/**
* Maximum number of invocations to reuse the same cache before refreshing it.
* Must be between 1 and 100.
*
* @default 10
*/
cacheIntervals: z
.number()
.int()
.min(1, { message: "cacheIntervals must be at least 1." })
.max(100, { message: "cacheIntervals must not exceed 100." })
.default(10),

/**
* Time-to-live for cache in seconds. Must be greater than 0.
* Default: 1800 (30 minutes).
*
* @default 1800
*/
ttlSeconds: z
.number()
.int()
.positive({ message: "ttlSeconds must be greater than 0." })
.default(1800),

/**
* Minimum estimated request tokens required to enable caching.
* Set higher to avoid caching small requests where overhead may exceed benefits.
*
* @default 0
*/
minTokens: z
.number()
.int()
.min(0, { message: "minTokens must be non-negative." })
.default(0),
});

/**
* Inferred TypeScript type for ContextCacheConfig properties.
*/
export type ContextCacheConfigProps = z.infer<typeof contextCacheConfigSchema>;

/**
* Configuration for context caching across all agents in an app.
*
* This configuration enables and controls context caching behavior for
* all LLM agents in an app. When this config is present on an app, context
* caching is enabled for all agents. When absent (null), context caching
* is disabled.
*
* Context caching can significantly reduce costs and improve response times
* by reusing previously processed context across multiple requests.
*/
export class ContextCacheConfig implements ContextCacheConfigProps {
/** Maximum number of invocations to reuse the same cache before refreshing it. */
public cacheIntervals: number;

/** Time-to-live for cache in seconds. */
public ttlSeconds: number;

/** Minimum estimated request tokens required to enable caching. */
public minTokens: number;

/**
* Creates a new validated ContextCacheConfig instance.
*
*/
constructor(params: Partial<ContextCacheConfigProps> = {}) {
const validated = contextCacheConfigSchema.parse(params);
this.cacheIntervals = validated.cacheIntervals;
this.ttlSeconds = validated.ttlSeconds;
this.minTokens = validated.minTokens;
}

/**
* Returns the TTL as a formatted string (e.g., "1800s").
*
*/
get ttlString(): string {
return `${this.ttlSeconds}s`;
}

/**
* Returns a readable string representation of the configuration,
* useful for debugging or logging.
*/
toString(): string {
return `ContextCacheConfig(cache_intervals=${this.cacheIntervals}, ttl=${this.ttlSeconds}s, min_tokens=${this.minTokens})`;
}

/**
* Validates a plain object and returns a new `ContextCacheConfig` instance.
*
*/
static from(data: unknown): ContextCacheConfig {
const validated = contextCacheConfigSchema.parse(data);
return new ContextCacheConfig(validated);
}

/**
* Converts the configuration to a plain JavaScript object.
*
*/
toJSON(): ContextCacheConfigProps {
return {
cacheIntervals: this.cacheIntervals,
ttlSeconds: this.ttlSeconds,
minTokens: this.minTokens,
};
}
}
15 changes: 8 additions & 7 deletions packages/adk/src/agents/index.ts
Original file line number Diff line number Diff line change
@@ -1,11 +1,12 @@
export * from "./agent-builder";
export * from "./base-agent";
export * from "./callback-context";
export * from "./context-cache-config";
export * from "./invocation-context";
export * from "./lang-graph-agent";
export * from "./llm-agent";
export * from "./sequential-agent";
export * from "./parallel-agent";
export * from "./loop-agent";
export * from "./lang-graph-agent";
export * from "./agent-builder";
export * from "./run-config";
export * from "./invocation-context";
export * from "./parallel-agent";
export * from "./readonly-context";
export * from "./callback-context";
export * from "./run-config";
export * from "./sequential-agent";
5 changes: 5 additions & 0 deletions packages/adk/src/agents/invocation-context.ts
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,7 @@ import type { BaseSessionService } from "../sessions/base-session-service";
import type { Session } from "../sessions/session";
import type { ActiveStreamingTool } from "./active-streaming-tool";
import type { BaseAgent } from "./base-agent";
import { ContextCacheConfig } from "./context-cache-config";
import type { LiveRequestQueue } from "./live-request-queue";
import type { RunConfig } from "./run-config";
import type { TranscriptionEntry } from "./transcription-entry";
Expand Down Expand Up @@ -103,6 +104,7 @@ export class InvocationContext {
readonly artifactService?: BaseArtifactService;
readonly sessionService: BaseSessionService;
readonly memoryService?: BaseMemoryService;
readonly contextCacheConfig?: ContextCacheConfig;

/**
* The id of this invocation context. Readonly.
Expand Down Expand Up @@ -186,6 +188,7 @@ export class InvocationContext {
activeStreamingTools?: Record<string, ActiveStreamingTool>;
transcriptionCache?: TranscriptionEntry[];
runConfig?: RunConfig;
contextCacheConfig?: ContextCacheConfig;
}) {
this.artifactService = options.artifactService;
this.sessionService = options.sessionService;
Expand All @@ -200,6 +203,7 @@ export class InvocationContext {
this.activeStreamingTools = options.activeStreamingTools;
this.transcriptionCache = options.transcriptionCache;
this.runConfig = options.runConfig;
this.contextCacheConfig = options.contextCacheConfig;
}

/**
Expand Down Expand Up @@ -245,6 +249,7 @@ export class InvocationContext {
activeStreamingTools: this.activeStreamingTools,
transcriptionCache: this.transcriptionCache,
runConfig: this.runConfig,
contextCacheConfig: this.contextCacheConfig,
});
}
}
7 changes: 7 additions & 0 deletions packages/adk/src/agents/llm-agent.ts
Original file line number Diff line number Diff line change
Expand Up @@ -23,6 +23,7 @@ import {
type BeforeAgentCallback,
} from "./base-agent";
import type { CallbackContext } from "./callback-context";
import { ContextCacheConfig } from "./context-cache-config";
import type { InvocationContext } from "./invocation-context";
import type { ReadonlyContext } from "./readonly-context";

Expand Down Expand Up @@ -252,6 +253,11 @@ export interface LlmAgentConfig<T extends BaseLlm = BaseLlm> {
* Callback or list of callbacks to be called after calling a tool
*/
afterToolCallback?: AfterToolCallback;

/**
* Context cache configuration for Gemini models
*/
contextCacheConfig?: ContextCacheConfig;
}

/**
Expand Down Expand Up @@ -382,6 +388,7 @@ export class LlmAgent<T extends BaseLlm = BaseLlm> extends BaseAgent {
subAgents: config.subAgents,
beforeAgentCallback: config.beforeAgentCallback,
afterAgentCallback: config.afterAgentCallback,
contextCacheConfig: config.contextCacheConfig,
});

this.model = config.model || "";
Expand Down
4 changes: 3 additions & 1 deletion packages/adk/src/flows/llm-flows/base-llm-flow.ts
Original file line number Diff line number Diff line change
Expand Up @@ -77,7 +77,9 @@ export abstract class BaseLlmFlow {
async *_runOneStepAsync(
invocationContext: InvocationContext,
): AsyncGenerator<Event> {
const llmRequest = new LlmRequest();
const llmRequest = new LlmRequest({
cacheConfig: invocationContext.contextCacheConfig,
});

// Preprocessing phase
for await (const event of this._preprocessAsync(
Expand Down
Loading