Skip to content

Commit 4d46a27

Browse files
authored
UpdateContext.md (#1844)
* UpdateContext.md * Update index.md * Update index.md noticed that the hierarchy of bullet points was not correct * Update context and callbackcontext.md
1 parent 8b9b8ba commit 4d46a27

1 file changed

Lines changed: 58 additions & 43 deletions

File tree

docs/context/index.md

Lines changed: 58 additions & 43 deletions
Original file line numberDiff line numberDiff line change
@@ -108,15 +108,28 @@ The central piece holding all this information together for a single, complete u
108108
}
109109
```
110110

111-
## The Different types of Context
111+
## Types of context
112112

113-
While `InvocationContext` acts as the comprehensive internal container, ADK provides specialized context objects tailored to specific situations. This ensures you have the right tools and permissions for the task at hand without needing to handle the full complexity of the internal context everywhere. Here are the different "flavors" you'll encounter:
113+
ADK uses the `Context` class as the central mechanism to manage an agent's environment, state, and resources. While `Context` serves as the foundational base for all agent interactions, it manifests in specialized "flavors" designed to provide the right balance of capabilities and permissions depending on where they are used in the agent's execution flow.
114+
If you use these specific context types, ADK ensures that your agent has access to necessary information, such as memory, session state, or credentials, exactly when and where you need them.
115+
Here are the primary context flavors you will encounter:
114116

115-
1. **`InvocationContext`**
116-
* **Where Used:** Received as the `ctx` argument directly within an agent's core implementation methods (`_run_async_impl`, `_run_live_impl`).
117-
* **Purpose:** Provides access to the *entire* state of the current invocation. This is the most comprehensive context object.
118-
* **Key Contents:** Direct access to `session` (including `state` and `events`), the current `agent` instance, `invocation_id`, initial `user_content`, references to configured services (`artifact_service`, `memory_service`, `session_service`), and fields related to live/streaming modes.
119-
* **Use Case:** Primarily used when the agent's core logic needs direct access to the overall session or services, though often state and artifact interactions are delegated to callbacks/tools which use their own contexts. Also used to control the invocation itself (e.g., setting `ctx.end_invocation = True`).
117+
- **`InvocationContext`**: Used during core agent runs (`_run_async_impl`, `_run_live_impl`) to provide a comprehensive view of the entire invocation, including service references and lifecycle management.
118+
119+
- **`ReadonlyContext`**: A lightweight, restricted view of fundamental contextual details used in scenarios where mutation is disallowed, such as within instruction providers.
120+
121+
- **`Context`**: Used in agent lifecycle and model callbacks. It provides a robust set of features for reading/writing session state, managing artifacts, and injecting data into the memory service.
122+
123+
- **`ToolContext`**: Tailored for tool execution and tool-related callbacks. In addition to the capabilities of Context, it includes specialized methods for authentication flows, memory searching, and artifact discovery.
124+
125+
!!! note
126+
**About compatibility**: In Python and TypeScript, `CallbackContext` and `ToolContext` have been replaced by the `Context` type. The `CallbackContext` class is maintained as an alias for `Context` to ensure backward compatibility. While you may encounter `CallbackContext` in existing codebases, **you should use the `Context` class** for all new development to take advantage of the full, unified feature set.
127+
128+
### `InvocationContext`
129+
- **Where Used:** Received as the `ctx` argument directly within an agent's core implementation methods (`_run_async_impl`, `_run_live_impl`).
130+
- **Purpose:** Provides access to the entire state of the current invocation. This is the most comprehensive context object.
131+
- **Key Contents:** Direct access to `session` (including `state` and `events`), the current `agent` instance, `invocation_id`, initial `user_content`, references to configured services (`artifact_service`, `memory_service`, `session_service`), and fields related to live/streaming modes.
132+
- **Use Case:** Primarily used when the agent's core logic needs direct access to the overall session or services, though often state and artifact interactions are delegated to callbacks/tools which use their own contexts. Also used to control the invocation itself (e.g., setting `ctx.end_invocation = True`).
120133

121134
=== "Python"
122135

@@ -136,7 +149,7 @@ While `InvocationContext` acts as the comprehensive internal container, ADK prov
136149
# ... agent logic using ctx ...
137150
yield # ... event ...
138151
```
139-
152+
140153
=== "TypeScript"
141154

142155
```typescript
@@ -189,10 +202,10 @@ While `InvocationContext` acts as the comprehensive internal container, ADK prov
189202
}
190203
```
191204

192-
2. **`ReadonlyContext`**
193-
* **Where Used:** Provided in scenarios where only read access to basic information is needed and mutation is disallowed (e.g., `InstructionProvider` functions). It's also the base class for other contexts.
194-
* **Purpose:** Offers a safe, read-only view of fundamental contextual details.
195-
* **Key Contents:** `invocation_id`, `agent_name`, and a read-only *view* of the current `state`.
205+
### `ReadonlyContext`
206+
- **Where Used:** Provided in scenarios where only read access to basic information is needed and mutation is disallowed (e.g., `InstructionProvider` functions). It's also the base class for other contexts.
207+
- **Purpose:** Offers a safe, read-only view of fundamental contextual details.
208+
- **Key Contents:** `invocation_id`, `agent_name`, and a read-only *view* of the current `state`.
196209

197210
=== "Python"
198211

@@ -246,15 +259,17 @@ While `InvocationContext` acts as the comprehensive internal container, ADK prov
246259
}
247260
```
248261

249-
3. **`CallbackContext`**
250-
* **Where Used:** Passed as `callback_context` to agent lifecycle callbacks (`before_agent_callback`, `after_agent_callback`) and model interaction callbacks (`before_model_callback`, `after_model_callback`).
251-
* **Purpose:** Facilitates inspecting and modifying state, interacting with artifacts, and accessing invocation details *specifically within callbacks*.
252-
* **Key Capabilities (Adds to `ReadonlyContext`):**
253-
* **Mutable `state` Property:** Allows reading *and writing* to session state. Changes made here (`callback_context.state['key'] = value`) are tracked and associated with the event generated by the framework after the callback.
254-
* **Artifact Methods:** `load_artifact(filename)` and `save_artifact(filename, part)` methods for interacting with the configured `artifact_service`.
255-
* Direct `user_content` access.
256-
257-
*(Note: In TypeScript, `CallbackContext` and `ToolContext` are unified into a single `Context` type.)*
262+
### `CallbackContext` and `Context`
263+
264+
- **Where Used:** Passed as `callback_context` to agent lifecycle callbacks (`before_agent_callback`, `after_agent_callback`) and model interaction callbacks (`before_model_callback`, `after_model_callback`).
265+
- **Purpose:** Facilitates inspecting and modifying state, interacting with artifacts, and accessing invocation details *specifically within callbacks*.
266+
- **Key Capabilities (Adds to `ReadonlyContext`):**
267+
- **Mutable `state` Property:** Allows reading and writing to session state. Changes made here (`callback_context.state['key'] = value`) are tracked and associated with the event generated by the framework after the callback.
268+
- **Artifact Methods:** `load_artifact(filename)` and `save_artifact(filename, part)` methods for interacting with the configured `artifact_service`.
269+
- Direct `user_content` access.
270+
271+
!!! note
272+
In Python and TypeScript, `CallbackContext` and `ToolContext` have been replaced by the `Context` type.
258273

259274
=== "Python"
260275

@@ -327,15 +342,15 @@ While `InvocationContext` acts as the comprehensive internal container, ADK prov
327342
}
328343
```
329344

330-
4. **`ToolContext`**
331-
* **Where Used:** Passed as `tool_context` to the functions backing `FunctionTool`s and to tool execution callbacks (`before_tool_callback`, `after_tool_callback`).
332-
* **Purpose:** Provides everything `CallbackContext` does, plus specialized methods essential for tool execution, like handling authentication, searching memory, and listing artifacts.
333-
* **Key Capabilities (Adds to `CallbackContext`):**
334-
* **Authentication Methods:** `request_credential(auth_config)` to trigger an auth flow, and `get_auth_response(auth_config)` to retrieve credentials provided by the user/system.
335-
* **Artifact Listing:** `list_artifacts()` to discover available artifacts in the session.
336-
* **Memory Search:** `search_memory(query)` to query the configured `memory_service`.
337-
* **`function_call_id` Property:** Identifies the specific function call from the LLM that triggered this tool execution, crucial for linking authentication requests or responses back correctly.
338-
* **`actions` Property:** Direct access to the `EventActions` object for this step, allowing the tool to signal state changes, auth requests, etc.
345+
### `ToolContext`
346+
- **Where Used:** Passed as `tool_context` to the functions backing `FunctionTool`s and to tool execution callbacks (`before_tool_callback`, `after_tool_callback`).
347+
- **Purpose:** Provides everything `CallbackContext` does, plus specialized methods essential for tool execution, like handling authentication, searching memory, and listing artifacts.
348+
- **Key Capabilities (Adds to `CallbackContext`):**
349+
- **Authentication Methods:** `request_credential(auth_config)` to trigger an auth flow, and `get_auth_response(auth_config)` to retrieve credentials provided by the user/system.
350+
- **Artifact Listing:** `list_artifacts()` to discover available artifacts in the session.
351+
- **Memory Search:** `search_memory(query)` to query the configured `memory_service`.
352+
- **`function_call_id` Property:** Identifies the specific function call from the LLM that triggered this tool execution, crucial for linking authentication requests or responses back correctly.
353+
- **`actions` Property:** Direct access to the `EventActions` object for this step, allowing the tool to signal state changes, auth requests, etc.
339354

340355
=== "Python"
341356

@@ -434,15 +449,15 @@ While `InvocationContext` acts as the comprehensive internal container, ADK prov
434449
Understanding these different context objects and when to use them is key to effectively managing state, accessing services, and controlling the flow of your ADK application. The next section will detail common tasks you can perform using these contexts.
435450

436451

437-
## Common Tasks Using Context
452+
## Common tasks using context
438453

439454
Now that you understand the different context objects, let's focus on how to use them for common tasks when building your agents and tools.
440455

441-
### Accessing Information
456+
### Access information
442457

443458
You'll frequently need to read information stored within the context.
444459

445-
* **Reading Session State:** Access data saved in previous steps or user/app-level settings. Use dictionary-like access on the `state` property.
460+
* **Read session state:** Access data saved in previous steps or user/app-level settings. Use dictionary-like access on the `state` property.
446461

447462
=== "Python"
448463

@@ -544,7 +559,7 @@ You'll frequently need to read information stored within the context.
544559
}
545560
```
546561

547-
* **Getting Current Identifiers:** Useful for logging or custom logic based on the current operation.
562+
* **Get current identifiers:** Useful for logging or custom logic based on the current operation.
548563

549564
=== "Python"
550565

@@ -597,7 +612,7 @@ You'll frequently need to read information stored within the context.
597612
}
598613
```
599614

600-
* **Accessing the Initial User Input:** Refer back to the message that started the current invocation.
615+
* **Access the initial user input:** Refer back to the message that started the current invocation.
601616

602617
=== "Python"
603618

@@ -665,13 +680,13 @@ You'll frequently need to read information stored within the context.
665680
}
666681
```
667682

668-
### Managing State
683+
### Manage state
669684

670685
State is crucial for memory and data flow. When you modify state using `CallbackContext` or `ToolContext`, the changes are automatically tracked and persisted by the framework.
671686

672687
* **How it Works:** Writing to `callback_context.state['my_key'] = my_value` or `tool_context.state['my_key'] = my_value` adds this change to the `EventActions.state_delta` associated with the current step's event. The `SessionService` then applies these deltas when persisting the event.
673688

674-
* **Passing Data Between Tools**
689+
* **Pass data between tools**
675690

676691
=== "Python"
677692

@@ -761,7 +776,7 @@ State is crucial for memory and data flow. When you modify state using `Callback
761776
}
762777
```
763778

764-
* **Updating User Preferences:**
779+
* **Update user preferences:**
765780

766781
=== "Python"
767782

@@ -815,13 +830,13 @@ State is crucial for memory and data flow. When you modify state using `Callback
815830
}
816831
```
817832

818-
* **State Prefixes:** While basic state is session-specific, prefixes like `app:` and `user:` can be used with persistent `SessionService` implementations (like `DatabaseSessionService` or `VertexAiSessionService`) to indicate broader scope (app-wide or user-wide across sessions). `temp:` can denote data only relevant within the current invocation.
833+
* **State prefixes:** While basic state is session-specific, prefixes like `app:` and `user:` can be used with persistent `SessionService` implementations (like `DatabaseSessionService` or `VertexAiSessionService`) to indicate broader scope (app-wide or user-wide across sessions). `temp:` can denote data only relevant within the current invocation.
819834

820-
### Working with Artifacts
835+
### Work with artifacts
821836

822837
Use artifacts to handle files or large data blobs associated with the session. Common use case: processing uploaded documents.
823838

824-
* **Document Summarizer Example Flow:**
839+
* **Document summarizer example flow:**
825840

826841
1. **Ingest Reference (e.g., in a Setup Tool or Callback):** Save the *path or URI* of the document, not the entire content, as an artifact.
827842

@@ -1082,7 +1097,7 @@ Use artifacts to handle files or large data blobs associated with the session. C
10821097
}
10831098
```
10841099

1085-
* **Listing Artifacts:** Discover what files are available.
1100+
* **List Artifacts:** Discover what files are available.
10861101

10871102
=== "Python"
10881103

@@ -1144,7 +1159,7 @@ Use artifacts to handle files or large data blobs associated with the session. C
11441159
}
11451160
```
11461161

1147-
### Handling Tool Authentication
1162+
### Handle tool authentication
11481163

11491164
<div class="language-support-tag">
11501165
<span class="lst-supported">Supported in ADK</span><span class="lst-python">Python v0.1.0</span><span class="lst-typescript">TypeScript v0.2.0</span><span class="lst-java">Java v0.2.0</span>

0 commit comments

Comments
 (0)