> {
- try {
- const artifactKeys = await toolContext.listArtifacts();
- console.log(`Available artifacts: ${artifactKeys}`);
- return { available_docs: artifactKeys };
- } catch (e) {
- return { error: `Artifact service error: ${e}` };
- }
- }
- ```
-
-### Handling Tool Authentication
+### Handling Tool Authentication
- Supported in ADKPython v0.1.0
+ Supported in ADKPython v0.1.0TypeScript v0.2.0
Securely manage API keys or other credentials needed by tools.
-```python
-# Pseudocode: Tool requiring auth
-from google.adk.tools import ToolContext
-from google.adk.auth import AuthConfig # Assume appropriate AuthConfig is defined
+=== "Python"
-# Define your required auth configuration (e.g., OAuth, API Key)
-MY_API_AUTH_CONFIG = AuthConfig(...)
-AUTH_STATE_KEY = "user:my_api_credential" # Key to store retrieved credential
+ ```python
+ # Pseudocode: Tool requiring auth
+ from google.adk.tools import ToolContext
+ from google.adk.auth import AuthConfig # Assume appropriate AuthConfig is defined
-def call_secure_api(tool_context: ToolContext, request_data: str) -> dict:
- # 1. Check if credential already exists in state
- credential = tool_context.state.get(AUTH_STATE_KEY)
+ # Define your required auth configuration (e.g., OAuth, API Key)
+ MY_API_AUTH_CONFIG = AuthConfig(...)
+ AUTH_STATE_KEY = "user:my_api_credential" # Key to store retrieved credential
- if not credential:
- # 2. If not, request it
- print("Credential not found, requesting...")
- try:
- tool_context.request_credential(MY_API_AUTH_CONFIG)
- # The framework handles yielding the event. The tool execution stops here for this turn.
- return {"status": "Authentication required. Please provide credentials."}
- except ValueError as e:
- return {"error": f"Auth error: {e}"} # e.g., function_call_id missing
- except Exception as e:
- return {"error": f"Failed to request credential: {e}"}
+ def call_secure_api(tool_context: ToolContext, request_data: str) -> dict:
+ # 1. Check if credential already exists in state
+ credential = tool_context.state.get(AUTH_STATE_KEY)
- # 3. If credential exists (might be from a previous turn after request)
- # or if this is a subsequent call after auth flow completed externally
- try:
- # Optionally, re-validate/retrieve if needed, or use directly
- # This might retrieve the credential if the external flow just completed
- auth_credential_obj = tool_context.get_auth_response(MY_API_AUTH_CONFIG)
- api_key = auth_credential_obj.api_key # Or access_token, etc.
+ if not credential:
+ # 2. If not, request it
+ print("Credential not found, requesting...")
+ try:
+ tool_context.request_credential(MY_API_AUTH_CONFIG)
+ # The framework handles yielding the event. The tool execution stops here for this turn.
+ return {"status": "Authentication required. Please provide credentials."}
+ except ValueError as e:
+ return {"error": f"Auth error: {e}"} # e.g., function_call_id missing
+ except Exception as e:
+ return {"error": f"Failed to request credential: {e}"}
- # Store it back in state for future calls within the session
- tool_context.state[AUTH_STATE_KEY] = auth_credential_obj.model_dump() # Persist retrieved credential
+ # 3. If credential exists (might be from a previous turn after request)
+ # or if this is a subsequent call after auth flow completed externally
+ try:
+ # Optionally, re-validate/retrieve if needed, or use directly
+ # This might retrieve the credential if the external flow just completed
+ auth_credential_obj = tool_context.get_auth_response(MY_API_AUTH_CONFIG)
+ api_key = auth_credential_obj.api_key # Or access_token, etc.
- print(f"Using retrieved credential to call API with data: {request_data}")
- # ... Make the actual API call using api_key ...
- api_result = f"API result for {request_data}"
+ # Store it back in state for future calls within the session
+ tool_context.state[AUTH_STATE_KEY] = auth_credential_obj.model_dump() # Persist retrieved credential
- return {"result": api_result}
- except Exception as e:
- # Handle errors retrieving/using the credential
- print(f"Error using credential: {e}")
- # Maybe clear the state key if credential is invalid?
- # tool_context.state[AUTH_STATE_KEY] = None
- return {"error": "Failed to use credential"}
+ print(f"Using retrieved credential to call API with data: {request_data}")
+ # ... Make the actual API call using api_key ...
+ api_result = f"API result for {request_data}"
-```
+ return {"result": api_result}
+ except Exception as e:
+ # Handle errors retrieving/using the credential
+ print(f"Error using credential: {e}")
+ # Maybe clear the state key if credential is invalid?
+ # tool_context.state[AUTH_STATE_KEY] = None
+ return {"error": "Failed to use credential"}
+ ```
- === "TypeScript"
+=== "TypeScript"
```typescript
// Pseudocode: Tool requiring auth
import { ToolContext } from '@google/adk'; // AuthConfig from ADK or custom
-
+
// Define a local AuthConfig interface as it's not publicly exported by ADK
interface AuthConfig {
credentialKey: string;
authScheme: { type: string }; // Minimal representation for the example
// Add other properties if they become relevant for the example
}
-
+
// Define your required auth configuration (e.g., OAuth, API Key)
const MY_API_AUTH_CONFIG: AuthConfig = {
credentialKey: 'my-api-key', // Example key
@@ -1299,37 +1300,40 @@ def call_secure_api(tool_context: ToolContext, request_data: str) -> dict:
}
}
```
+
*Remember: `request_credential` pauses the tool and signals the need for authentication. The user/system provides credentials, and on a subsequent call, `get_auth_response` (or checking state again) allows the tool to proceed.* The `tool_context.function_call_id` is used implicitly by the framework to link the request and response.
-### Leveraging Memory
+### Leveraging Memory
- Supported in ADKPython v0.1.0
+ Supported in ADKPython v0.1.0TypeScript v0.2.0
Access relevant information from the past or external sources.
-```python
-# Pseudocode: Tool using memory search
-from google.adk.tools import ToolContext
-
-def find_related_info(tool_context: ToolContext, topic: str) -> dict:
- try:
- search_results = tool_context.search_memory(f"Information about {topic}")
- if search_results.results:
- print(f"Found {len(search_results.results)} memory results for '{topic}'")
- # Process search_results.results (which are SearchMemoryResponseEntry)
- top_result_text = search_results.results[0].text
- return {"memory_snippet": top_result_text}
- else:
- return {"message": "No relevant memories found."}
- except ValueError as e:
- return {"error": f"Memory service error: {e}"} # e.g., Service not configured
- except Exception as e:
- return {"error": f"Unexpected error searching memory: {e}"}
-```
+=== "Python"
- === "TypeScript"
+ ```python
+ # Pseudocode: Tool using memory search
+ from google.adk.tools import ToolContext
+
+ def find_related_info(tool_context: ToolContext, topic: str) -> dict:
+ try:
+ search_results = tool_context.search_memory(f"Information about {topic}")
+ if search_results.results:
+ print(f"Found {len(search_results.results)} memory results for '{topic}'")
+ # Process search_results.results (which are SearchMemoryResponseEntry)
+ top_result_text = search_results.results[0].text
+ return {"memory_snippet": top_result_text}
+ else:
+ return {"message": "No relevant memories found."}
+ except ValueError as e:
+ return {"error": f"Memory service error: {e}"} # e.g., Service not configured
+ except Exception as e:
+ return {"error": f"Unexpected error searching memory: {e}"}
+ ```
+
+=== "TypeScript"
```typescript
// Pseudocode: Tool using memory search
@@ -1352,40 +1356,42 @@ def find_related_info(tool_context: ToolContext, topic: str) -> dict:
}
```
-### Advanced: Direct `InvocationContext` Usage
+### Advanced: Direct `InvocationContext` Usage
- Supported in ADKPython v0.1.0
+ Supported in ADKPython v0.1.0TypeScript v0.2.0
While most interactions happen via `CallbackContext` or `ToolContext`, sometimes the agent's core logic (`_run_async_impl`/`_run_live_impl`) needs direct access.
-```python
-# Pseudocode: Inside agent's _run_async_impl
-from google.adk.agents import BaseAgent
-from google.adk.agents.invocation_context import InvocationContext
-from google.adk.events import Event
-from typing import AsyncGenerator
-
-class MyControllingAgent(BaseAgent):
- async def _run_async_impl(self, ctx: InvocationContext) -> AsyncGenerator[Event, None]:
- # Example: Check if a specific service is available
- if not ctx.memory_service:
- print("Memory service is not available for this invocation.")
- # Potentially change agent behavior
-
- # Example: Early termination based on some condition
- if ctx.session.state.get("critical_error_flag"):
- print("Critical error detected, ending invocation.")
- ctx.end_invocation = True # Signal framework to stop processing
- yield Event(author=self.name, invocation_id=ctx.invocation_id, content="Stopping due to critical error.")
- return # Stop this agent's execution
-
- # ... Normal agent processing ...
- yield # ... event ...
-```
+=== "Python"
- === "TypeScript"
+ ```python
+ # Pseudocode: Inside agent's _run_async_impl
+ from google.adk.agents import BaseAgent
+ from google.adk.agents.invocation_context import InvocationContext
+ from google.adk.events import Event
+ from typing import AsyncGenerator
+
+ class MyControllingAgent(BaseAgent):
+ async def _run_async_impl(self, ctx: InvocationContext) -> AsyncGenerator[Event, None]:
+ # Example: Check if a specific service is available
+ if not ctx.memory_service:
+ print("Memory service is not available for this invocation.")
+ # Potentially change agent behavior
+
+ # Example: Early termination based on some condition
+ if ctx.session.state.get("critical_error_flag"):
+ print("Critical error detected, ending invocation.")
+ ctx.end_invocation = True # Signal framework to stop processing
+ yield Event(author=self.name, invocation_id=ctx.invocation_id, content="Stopping due to critical error.")
+ return # Stop this agent's execution
+
+ # ... Normal agent processing ...
+ yield # ... event ...
+ ```
+
+=== "TypeScript"
```typescript
// Pseudocode: Inside agent's runAsyncImpl
diff --git a/docs/events/index.md b/docs/events/index.md
index fdb9d2939..c8c1b62c0 100644
--- a/docs/events/index.md
+++ b/docs/events/index.md
@@ -1,7 +1,7 @@
# Events
- Supported in ADKPython v0.1.0Go v0.1.0Java v0.1.0
+ Supported in ADKPython v0.1.0TypeScript v0.2.0Go v0.1.0Java v0.1.0
Events are the fundamental units of information flow within the Agent Development Kit (ADK). They represent every significant occurrence during an agent's interaction lifecycle, from initial user input to the final response and all the steps in between. Understanding events is crucial because they are the primary way components communicate, state is managed, and control flow is directed.
@@ -257,7 +257,7 @@ Once you know the event type, access the relevant data:
* **Function Call Details:**
=== "Python"
-
+
```python
calls = event.get_function_calls()
if calls:
diff --git a/docs/grounding/google_search_grounding.md b/docs/grounding/google_search_grounding.md
index b011458e8..31d939dd5 100644
--- a/docs/grounding/google_search_grounding.md
+++ b/docs/grounding/google_search_grounding.md
@@ -1,5 +1,9 @@
# Understanding Google Search Grounding
+
+ Supported in ADKPython v0.1.0TypeScript v0.2.0
+
+
[Google Search Grounding tool](../tools/built-in-tools.md#google-search) is a powerful feature in the Agent Development Kit (ADK) that enables AI agents to access real-time, authoritative information from the web. By connecting your agents to Google Search, you can provide users with up-to-date answers backed by reliable sources.
This feature is particularly valuable for queries requiring current information like weather updates, news events, stock prices, or any facts that may have changed since the model's training data cutoff. When your agent determines that external information is needed, it automatically performs web searches and incorporates the results into its response with proper attribution.
@@ -82,7 +86,7 @@ Under a project directory, run the following commands:
echo "from . import agent" > google_search_agent/__init__.py
# Step 3: Create an agent.py (the agent definition) and .env (Gemini authentication config)
- type nul > google_search_agent\agent.py
+ type nul > google_search_agent\agent.py
type nul > google_search_agent\.env
```
@@ -188,7 +192,7 @@ There are multiple ways to interact with your agent:
```shell
adk web
```
-
+
!!!info "Note for Windows users"
When hitting the `_make_subprocess_transport NotImplementedError`, consider using `adk web --no-reload` instead.
@@ -217,7 +221,7 @@ There are multiple ways to interact with your agent:
```
To exit, use Cmd/Ctrl+C.
-### 📝 Example prompts to try
+### Example prompts to try
With those questions, you can confirm that the agent is actually calling Google Search
to get the latest weather and time.
@@ -245,18 +249,18 @@ This diagram illustrates the step-by-step process of how a user query results in
The grounding agent uses the data flow described in the diagram to retrieve, process, and incorporate external information into the final answer presented to the user.
-1. **User Query**: An end-user interacts with your agent by asking a question or giving a command.
-2. **ADK Orchestration** : The Agent Development Kit orchestrates the agent's behavior and passes the user's message to the core of your agent.
-3. **LLM Analysis and Tool-Calling** : The agent's LLM (e.g., a Gemini model) analyzes the prompt. If it determines that external, up-to-date information is required, it triggers the grounding mechanism by calling the
- google\_search tool. This is ideal for answering queries about recent news, weather, or facts not present in the model's training data.
-4. **Grounding Service Interaction** : The google\_search tool interacts with an internal grounding service that formulates and sends one or more queries to the Google Search Index.
-5. **Context Injection**: The grounding service retrieves the relevant web pages and snippets. It then integrates these search results into the model's context
- before the final response is generated. This crucial step allows the model to "reason" over factual, real-time data.
-6. **Grounded Response Generation**: The LLM, now informed by the fresh search results, generates a response that incorporates the retrieved information.
-7. **Response Presentation with Sources** : The ADK receives the final grounded response, which includes the necessary source URLs and
+1. **User Query**: An end-user interacts with your agent by asking a question or giving a command.
+2. **ADK Orchestration** : The Agent Development Kit orchestrates the agent's behavior and passes the user's message to the core of your agent.
+3. **LLM Analysis and Tool-Calling** : The agent's LLM (e.g., a Gemini model) analyzes the prompt. If it determines that external, up-to-date information is required, it triggers the grounding mechanism by calling the
+ google\_search tool. This is ideal for answering queries about recent news, weather, or facts not present in the model's training data.
+4. **Grounding Service Interaction** : The google\_search tool interacts with an internal grounding service that formulates and sends one or more queries to the Google Search Index.
+5. **Context Injection**: The grounding service retrieves the relevant web pages and snippets. It then integrates these search results into the model's context
+ before the final response is generated. This crucial step allows the model to "reason" over factual, real-time data.
+6. **Grounded Response Generation**: The LLM, now informed by the fresh search results, generates a response that incorporates the retrieved information.
+7. **Response Presentation with Sources** : The ADK receives the final grounded response, which includes the necessary source URLs and
groundingMetadata, and presents it to the user with attribution. This allows end-users to verify the information and builds trust in the agent's answers.
-### Understanding grounding with Google Search response
+### Understanding grounding with Google Search response
When the agent uses Google Search to ground a response, it returns a detailed set of information that includes not only the final text answer but also the sources it used to generate that answer. This metadata is crucial for verifying the response and for providing attribution to the original sources.
@@ -314,9 +318,9 @@ The following is an example of the content object returned by the model after a
The metadata provides a link between the text generated by the model and the sources that support it. Here is a step-by-step breakdown:
-1. **groundingChunks**: This is a list of the web pages the model consulted. Each chunk contains the title of the webpage and a uri that links to the source.
-2. **groundingSupports**: This list connects specific sentences in the final answer back to the groundingChunks.
- * **segment**: This object identifies a specific portion of the final text answer, defined by its startIndex, endIndex, and the text itself.
+1. **groundingChunks**: This is a list of the web pages the model consulted. Each chunk contains the title of the webpage and a uri that links to the source.
+2. **groundingSupports**: This list connects specific sentences in the final answer back to the groundingChunks.
+ * **segment**: This object identifies a specific portion of the final text answer, defined by its startIndex, endIndex, and the text itself.
* **groundingChunkIndices**: This array contains the index numbers that correspond to the sources listed in the groundingChunks. For example, the sentence "They defeated FC Porto 2-1..." is supported by information from groundingChunks at index 0 and 1 (both from mlssoccer.com and intermiamicf.com).
### How to display grounding responses with Google Search
diff --git a/docs/grounding/vertex_ai_search_grounding.md b/docs/grounding/vertex_ai_search_grounding.md
index 7fbe9a053..adaae8254 100644
--- a/docs/grounding/vertex_ai_search_grounding.md
+++ b/docs/grounding/vertex_ai_search_grounding.md
@@ -1,5 +1,9 @@
# Understanding Vertex AI Search Grounding
+
+ Supported in ADKPython v0.1.0TypeScript v0.2.0
+
+
[Vertex AI Search Grounding tool](../tools/built-in-tools.md#vertex-ai-search) is a powerful feature in the Agent Development Kit (ADK) that enables AI agents to access information from your private enterprise documents and data repositories. By connecting your agents to indexed enterprise content, you can provide users with answers grounded in your organization's knowledge base.
This feature is particularly valuable for enterprise-specific queries requiring information from internal documentation, policies, research papers, or any proprietary content that has been indexed in your [Vertex AI Search](https://cloud.google.com/enterprise-search) datastore. When your agent determines that information from your knowledge base is needed, it automatically searches your indexed documents and incorporates the results into its response with proper attribution.
@@ -88,7 +92,7 @@ Under a project directory, run the following commands:
echo "from . import agent" > vertex_search_agent/__init__.py
# Step 3: Create an agent.py (the agent definition) and .env (authentication config)
- type nul > vertex_search_agent\agent.py
+ type nul > vertex_search_agent\agent.py
type nul > google_search_agent\.env
```
@@ -147,7 +151,7 @@ There are multiple ways to interact with your agent:
```shell
adk web
```
-
+
!!!info "Note for Windows users"
When hitting the `_make_subprocess_transport NotImplementedError`, consider using `adk web --no-reload` instead.
@@ -176,7 +180,7 @@ There are multiple ways to interact with your agent:
```
To exit, use Cmd/Ctrl+C.
-### 📝 Example prompts to try
+### Example prompts to try
With those questions, you can confirm that the agent is actually calling Vertex AI Search
to get information from the Alphabet reports:
@@ -305,7 +309,7 @@ Since grounding metadata is provided, you can choose to implement citation displ
for event in events:
if event.is_final_response():
print(event.content.parts[0].text)
-
+
# Optional: Show source count
if event.grounding_metadata:
print(f"\nBased on {len(event.grounding_metadata.grounding_chunks)} documents")
diff --git a/docs/mcp/index.md b/docs/mcp/index.md
index dd185ba18..41ac121f1 100644
--- a/docs/mcp/index.md
+++ b/docs/mcp/index.md
@@ -1,7 +1,7 @@
# Model Context Protocol (MCP)
- Supported in ADKPythonGoJava
+ Supported in ADKPythonTypeScriptGoJava
The
diff --git a/docs/release-notes.md b/docs/release-notes.md
index 17d4b1d25..c9e333226 100644
--- a/docs/release-notes.md
+++ b/docs/release-notes.md
@@ -4,5 +4,6 @@ You can find the release notes in the code repositories for each supported
language. For detailed information on ADK releases, see these locations:
* [ADK Python release notes](https://github.com/google/adk-python/releases)
+* [ADK TypeScript release notes](https://github.com/google/adk-js/releases)
* [ADK Go release notes](https://github.com/google/adk-go/releases)
* [ADK Java release notes](https://github.com/google/adk-java/releases)
diff --git a/docs/sessions/index.md b/docs/sessions/index.md
index 822147030..a33dd1eed 100644
--- a/docs/sessions/index.md
+++ b/docs/sessions/index.md
@@ -1,7 +1,7 @@
# Introduction to Conversational Context: Session, State, and Memory
- Supported in ADKPythonGoJava
+ Supported in ADKPythonTypeScriptGoJava
Meaningful, multi-turn conversations require agents to understand context. Just
diff --git a/docs/sessions/memory.md b/docs/sessions/memory.md
index f1398bd24..70e47ab87 100644
--- a/docs/sessions/memory.md
+++ b/docs/sessions/memory.md
@@ -1,11 +1,7 @@
# Memory: Long-Term Knowledge with `MemoryService`
- Supported in ADK
- Python v0.1.0
- Go v0.1.0
- Java v0.1.0
- Typescript v0.2.0
+ Supported in ADKPython v0.1.0Typescript v0.2.0Go v0.1.0Java v0.1.0
We've seen how `Session` tracks the history (`events`) and temporary data (`state`) for a *single, ongoing conversation*. But what if an agent needs to recall information from *past* conversations? This is where the concept of **Long-Term Knowledge** and the **`MemoryService`** come into play.
diff --git a/docs/sessions/session.md b/docs/sessions/session.md
index 48aa187a8..d7b941da5 100644
--- a/docs/sessions/session.md
+++ b/docs/sessions/session.md
@@ -1,11 +1,7 @@
# Session: Tracking Individual Conversations
- Supported in ADK
- Python v0.1.0
- Go v0.1.0
- Java v0.1.0
- Typescript v0.2.0
+ Supported in ADKPython v0.1.0Typescript v0.2.0Go v0.1.0Java v0.1.0
Following our Introduction, let's dive into the `Session`. Think back to the
@@ -67,6 +63,37 @@ are its key properties:
print("The final status of temp_service - ", temp_service)
```
+=== "TypeScript"
+
+ ```typescript
+ import { InMemorySessionService } from "@google/adk";
+
+ // Create a simple session to examine its properties
+ const tempService = new InMemorySessionService();
+ const exampleSession = await tempService.createSession({
+ appName: "my_app",
+ userId: "example_user",
+ state: {"initial_key": "initial_value"} // State can be initialized
+ });
+
+ console.log("--- Examining Session Properties ---");
+ console.log(`ID ('id'): ${exampleSession.id}`);
+ console.log(`Application Name ('appName'): ${exampleSession.appName}`);
+ console.log(`User ID ('userId'): ${exampleSession.userId}`);
+ console.log(`State ('state'): ${JSON.stringify(exampleSession.state)}`); // Note: Only shows initial state here
+ console.log(`Events ('events'): ${JSON.stringify(exampleSession.events)}`); // Initially empty
+ console.log(`Last Update ('lastUpdateTime'): ${exampleSession.lastUpdateTime}`);
+ console.log("---------------------------------");
+
+ // Clean up (optional for this example)
+ const finalStatus = await tempService.deleteSession({
+ appName: exampleSession.appName,
+ userId: exampleSession.userId,
+ sessionId: exampleSession.id
+ });
+ console.log("The final status of temp_service - ", finalStatus);
+ ```
+
=== "Go"
```go
@@ -104,37 +131,6 @@ are its key properties:
var unused = exampleSessionService.deleteSession(appName, userId, sessionId);
```
-=== "TypeScript"
-
- ```typescript
- import { InMemorySessionService } from "@google/adk";
-
- // Create a simple session to examine its properties
- const tempService = new InMemorySessionService();
- const exampleSession = await tempService.createSession({
- appName: "my_app",
- userId: "example_user",
- state: {"initial_key": "initial_value"} // State can be initialized
- });
-
- console.log("--- Examining Session Properties ---");
- console.log(`ID ('id'): ${exampleSession.id}`);
- console.log(`Application Name ('appName'): ${exampleSession.appName}`);
- console.log(`User ID ('userId'): ${exampleSession.userId}`);
- console.log(`State ('state'): ${JSON.stringify(exampleSession.state)}`); // Note: Only shows initial state here
- console.log(`Events ('events'): ${JSON.stringify(exampleSession.events)}`); // Initially empty
- console.log(`Last Update ('lastUpdateTime'): ${exampleSession.lastUpdateTime}`);
- console.log("---------------------------------");
-
- // Clean up (optional for this example)
- const finalStatus = await tempService.deleteSession({
- appName: exampleSession.appName,
- userId: exampleSession.userId,
- sessionId: exampleSession.id
- });
- console.log("The final status of temp_service - ", finalStatus);
- ```
-
*(**Note:** The state shown above is only the initial state. State updates
happen via events, as discussed in the State section.)*
@@ -179,6 +175,13 @@ the storage backend that best suits your needs:
from google.adk.sessions import InMemorySessionService
session_service = InMemorySessionService()
```
+ === "TypeScript"
+
+ ```typescript
+ import { InMemorySessionService } from "@google/adk";
+ const sessionService = new InMemorySessionService();
+ ```
+
=== "Go"
```go
@@ -194,16 +197,11 @@ the storage backend that best suits your needs:
InMemorySessionService exampleSessionService = new InMemorySessionService();
```
- === "TypeScript"
-
- ```typescript
- import { InMemorySessionService } from "@google/adk";
- const sessionService = new InMemorySessionService();
- ```
-
2. **`VertexAiSessionService`**
- { title="This feature is currently available for Python and Java. TypeScript support is planned/ coming soon."}
+
+ Supported in ADKPython v0.1.0Go v0.1.0Java v0.1.0
+
* **How it works:** Uses Google Cloud Vertex AI infrastructure via API
calls for session management.
@@ -283,11 +281,7 @@ the storage backend that best suits your needs:
3. **`DatabaseSessionService`**
- Supported in ADK
- Python v0.1.0
- Go v0.1.0
- Java v0.1.0
- Typescript v0.2.0
+ Supported in ADKPython v0.1.0Go v0.1.0
* **How it works:** Connects to a relational database (e.g., PostgreSQL,
diff --git a/docs/sessions/state.md b/docs/sessions/state.md
index 68e0f6dcd..c59a350ab 100644
--- a/docs/sessions/state.md
+++ b/docs/sessions/state.md
@@ -1,7 +1,7 @@
# State: The Session's Scratchpad
- Supported in ADKPython v0.1.0Go v0.1.0Java v0.1.0
+ Supported in ADKPython v0.1.0TypeScript v0.2.0Go v0.1.0Java v0.1.0
Within each `Session` (our conversation thread), the **`state`** attribute acts like the agent's dedicated scratchpad for that specific interaction. While `session.events` holds the full history, `session.state` is where the agent stores and updates dynamic details needed *during* the conversation.
@@ -102,12 +102,6 @@ To inject a value from the session state, enclose the key of the desired state v
# "Write a short story about a cat, focusing on the theme: friendship."
```
-=== "Go"
-
- ```go
- --8<-- "examples/go/snippets/sessions/instruction_template/instruction_template_example.go:key_template"
- ```
-
=== "TypeScript"
```typescript
@@ -119,9 +113,16 @@ To inject a value from the session state, enclose the key of the desired state v
instruction: "Write a short story about a cat, focusing on the theme: {topic}."
});
- // Assuming session.state['topic'] is set to "friendship", the LLM
+ // Assuming session.state['topic'] is set to "friendship", the LLM
// will receive the following instruction:
// "Write a short story about a cat, focusing on the theme: friendship."
+ ```
+
+=== "Go"
+
+ ```go
+ --8<-- "examples/go/snippets/sessions/instruction_template/instruction_template_example.go:key_template"
+ ```
#### Important Considerations
@@ -156,12 +157,6 @@ The `InstructionProvider` function receives a `ReadonlyContext` object, which yo
)
```
-=== "Go"
-
- ```go
- --8<-- "examples/go/snippets/sessions/instruction_provider/instruction_provider_example.go:bypass_state_injection"
- ```
-
=== "TypeScript"
```typescript
@@ -179,6 +174,13 @@ The `InstructionProvider` function receives a `ReadonlyContext` object, which yo
name: "template_helper_agent",
instruction: myInstructionProvider
});
+ ```
+
+=== "Go"
+
+ ```go
+ --8<-- "examples/go/snippets/sessions/instruction_provider/instruction_provider_example.go:bypass_state_injection"
+ ```
If you want to both use an `InstructionProvider` *and* inject state into your instructions, you can use the `inject_session_state` utility function.
@@ -275,18 +277,6 @@ This is the simplest method for saving an agent's final text response directly i
# Expected output might include: {'last_greeting': 'Hello there! How can I help you today?'}
```
-=== "Java"
-
- ```java
- --8<-- "examples/java/snippets/src/main/java/state/GreetingAgentExample.java:full_code"
- ```
-
-=== "Go"
-
- ```go
- --8<-- "examples/go/snippets/sessions/state_example/state_example.go:greeting"
- ```
-
=== "TypeScript"
```typescript
@@ -336,7 +326,19 @@ This is the simplest method for saving an agent's final text response directly i
const updatedSession = await sessionService.getSession({ appName, userId, sessionId });
console.log(`State after agent run: ${JSON.stringify(updatedSession?.state)}`);
// Expected output might include: {"last_greeting":"Hello there! How can I help you today?"}
+ ```
+=== "Go"
+
+ ```go
+ --8<-- "examples/go/snippets/sessions/state_example/state_example.go:greeting"
+ ```
+
+=== "Java"
+
+ ```java
+ --8<-- "examples/java/snippets/src/main/java/state/GreetingAgentExample.java:full_code"
+ ```
Behind the scenes, the `Runner` uses the `output_key` to create the necessary `EventActions` with a `state_delta` and calls `append_event`.
@@ -396,18 +398,6 @@ For more complex scenarios (updating multiple keys, non-string values, specific
# Note: 'temp:validation_needed' is NOT present.
```
-=== "Go"
-
- ```go
- --8<-- "examples/go/snippets/sessions/state_example/state_example.go:manual"
- ```
-
-=== "Java"
-
- ```java
- --8<-- "examples/java/snippets/src/main/java/state/ManualStateUpdateExample.java:full_code"
- ```
-
=== "TypeScript"
```typescript
@@ -463,6 +453,18 @@ For more complex scenarios (updating multiple keys, non-string values, specific
// Note: 'temp:validation_needed' is NOT present.
```
+=== "Go"
+
+ ```go
+ --8<-- "examples/go/snippets/sessions/state_example/state_example.go:manual"
+ ```
+
+=== "Java"
+
+ ```java
+ --8<-- "examples/java/snippets/src/main/java/state/ManualStateUpdateExample.java:full_code"
+ ```
+
**3. Via `CallbackContext` or `ToolContext` (Recommended for Callbacks and Tools)**
Modifying state within agent callbacks (e.g., `on_before_agent_call`, `on_after_agent_call`) or tool functions is best done using the `state` attribute of the `CallbackContext` or `ToolContext` provided to your function.
@@ -496,6 +498,28 @@ For more comprehensive details on context objects, refer to the [Context documen
# ... rest of callback/tool logic ...
```
+=== "TypeScript"
+
+ ```typescript
+ // In an agent callback or tool function
+ import { CallbackContext } from "@google/adk"; // or ToolContext
+
+ function myCallbackOrToolFunction(
+ context: CallbackContext, // Or ToolContext
+ // ... other parameters ...
+ ) {
+ // Update existing state
+ const count = context.state.get("user_action_count", 0);
+ context.state.set("user_action_count", count + 1);
+
+ // Add new state
+ context.state.set("temp:last_operation_status", "success");
+
+ // State changes are automatically part of the event's stateDelta
+ // ... rest of callback/tool logic ...
+ }
+ ```
+
=== "Go"
```go
@@ -524,28 +548,6 @@ For more comprehensive details on context objects, refer to the [Context documen
}
```
-=== "TypeScript"
-
- ```typescript
- // In an agent callback or tool function
- import { CallbackContext } from "@google/adk"; // or ToolContext
-
- function myCallbackOrToolFunction(
- context: CallbackContext, // Or ToolContext
- // ... other parameters ...
- ) {
- // Update existing state
- const count = context.state.get("user_action_count", 0);
- context.state.set("user_action_count", count + 1);
-
- // Add new state
- context.state.set("temp:last_operation_status", "success");
-
- // State changes are automatically part of the event's stateDelta
- // ... rest of callback/tool logic ...
- }
- ```
-
**What `append_event` Does:**
* Adds the `Event` to `session.events`.