You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
* UpdateContext.md
* Update index.md
* Update index.md
noticed that the hierarchy of bullet points was not correct
* Update context and callbackcontext.md
Copy file name to clipboardExpand all lines: docs/context/index.md
+58-43Lines changed: 58 additions & 43 deletions
Display the source diff
Display the rich diff
Original file line number
Diff line number
Diff line change
@@ -108,15 +108,28 @@ The central piece holding all this information together for a single, complete u
108
108
}
109
109
```
110
110
111
-
## The Different types of Context
111
+
## Types of context
112
112
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:
114
116
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`).
120
133
121
134
=== "Python"
122
135
@@ -136,7 +149,7 @@ While `InvocationContext` acts as the comprehensive internal container, ADK prov
136
149
# ... agent logic using ctx ...
137
150
yield # ... event ...
138
151
```
139
-
152
+
140
153
=== "TypeScript"
141
154
142
155
```typescript
@@ -189,10 +202,10 @@ While `InvocationContext` acts as the comprehensive internal container, ADK prov
189
202
}
190
203
```
191
204
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`.
196
209
197
210
=== "Python"
198
211
@@ -246,15 +259,17 @@ While `InvocationContext` acts as the comprehensive internal container, ADK prov
246
259
}
247
260
```
248
261
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.
258
273
259
274
=== "Python"
260
275
@@ -327,15 +342,15 @@ While `InvocationContext` acts as the comprehensive internal container, ADK prov
327
342
}
328
343
```
329
344
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.
339
354
340
355
=== "Python"
341
356
@@ -434,15 +449,15 @@ While `InvocationContext` acts as the comprehensive internal container, ADK prov
434
449
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.
435
450
436
451
437
-
## Common Tasks Using Context
452
+
## Common tasks using context
438
453
439
454
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.
440
455
441
-
### Accessing Information
456
+
### Access information
442
457
443
458
You'll frequently need to read information stored within the context.
444
459
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.
446
461
447
462
=== "Python"
448
463
@@ -544,7 +559,7 @@ You'll frequently need to read information stored within the context.
544
559
}
545
560
```
546
561
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.
548
563
549
564
=== "Python"
550
565
@@ -597,7 +612,7 @@ You'll frequently need to read information stored within the context.
597
612
}
598
613
```
599
614
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.
601
616
602
617
=== "Python"
603
618
@@ -665,13 +680,13 @@ You'll frequently need to read information stored within the context.
665
680
}
666
681
```
667
682
668
-
### Managing State
683
+
### Manage state
669
684
670
685
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.
671
686
672
687
***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.
673
688
674
-
***Passing Data Between Tools**
689
+
***Pass data between tools**
675
690
676
691
=== "Python"
677
692
@@ -761,7 +776,7 @@ State is crucial for memory and data flow. When you modify state using `Callback
761
776
}
762
777
```
763
778
764
-
***Updating User Preferences:**
779
+
***Update user preferences:**
765
780
766
781
=== "Python"
767
782
@@ -815,13 +830,13 @@ State is crucial for memory and data flow. When you modify state using `Callback
815
830
}
816
831
```
817
832
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.
819
834
820
-
### Working with Artifacts
835
+
### Work with artifacts
821
836
822
837
Use artifacts to handle files or large data blobs associated with the session. Common use case: processing uploaded documents.
823
838
824
-
***Document Summarizer Example Flow:**
839
+
***Document summarizer example flow:**
825
840
826
841
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.
827
842
@@ -1082,7 +1097,7 @@ Use artifacts to handle files or large data blobs associated with the session. C
1082
1097
}
1083
1098
```
1084
1099
1085
-
***Listing Artifacts:** Discover what files are available.
1100
+
***List Artifacts:** Discover what files are available.
1086
1101
1087
1102
=== "Python"
1088
1103
@@ -1144,7 +1159,7 @@ Use artifacts to handle files or large data blobs associated with the session. C
1144
1159
}
1145
1160
```
1146
1161
1147
-
### Handling Tool Authentication
1162
+
### Handle tool authentication
1148
1163
1149
1164
<divclass="language-support-tag">
1150
1165
<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