Thanks to visit codestin.com
Credit goes to github.com

Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
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
12 changes: 8 additions & 4 deletions examples/tools/loadmemory/main.go
Original file line number Diff line number Diff line change
Expand Up @@ -12,8 +12,8 @@
// See the License for the specific language governing permissions and
// limitations under the License.

// Package main provides an example ADK agent that uses the load_memory tool
// to search and retrieve memories from previous conversations.
// Package main provides an example ADK agent that uses the load_memory and
// preload_memory tools to retrieve memories from previous conversations.
package main

import (
Expand All @@ -34,6 +34,7 @@ import (
"google.golang.org/adk/session"
"google.golang.org/adk/tool"
"google.golang.org/adk/tool/loadmemorytool"
"google.golang.org/adk/tool/preloadmemorytool"
)

func main() {
Expand All @@ -51,10 +52,12 @@ func main() {
Model: model,
Description: "Agent that can recall information from memory.",
Instruction: "You are a helpful assistant with access to memory. " +
"When the user asks about something that might be in your memory, " +
"use the load_memory tool to search for relevant information. " +
"Relevant memory may be preloaded automatically for each request. " +
"If the preloaded context is not enough, use the load_memory tool " +
"to search for additional relevant information. " +
"If you find relevant memories, use them to provide informed responses.",
Tools: []tool.Tool{
preloadmemorytool.New(),
loadmemorytool.New(),
},
})
Expand All @@ -78,6 +81,7 @@ func main() {
}

fmt.Println("Memory populated with previous conversation about a trip to Tokyo.")
fmt.Println("Memories will be preloaded automatically for each request.")
fmt.Println("Try asking: 'What do you remember about my trip?'")

// Create a new session for the current conversation.
Expand Down
135 changes: 135 additions & 0 deletions tool/preloadmemorytool/tool.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,135 @@
// Copyright 2026 Google LLC
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.

// Package preloadmemorytool provides a tool that automatically preloads memory
// for the current user at the start of each LLM request.
//
// Unlike loadmemorytool which is called explicitly by the model, this tool
// runs automatically for each LLM request and injects relevant memory context
// into the system instructions.

package preloadmemorytool

import (
"fmt"
"strings"
"time"

"google.golang.org/adk/internal/utils"
"google.golang.org/adk/memory"
"google.golang.org/adk/model"
"google.golang.org/adk/tool"
)

const preloadInstructions = `The following content is from your previous conversations with the user.
They may be useful for answering the user's current query.
<PAST_CONVERSATIONS>
%s
</PAST_CONVERSATIONS>`

// preloadMemoryTool is a tool that preloads the memory for the current user.
// It is automatically executed for each LLM request and will not be called
// directly by the model.
type preloadMemoryTool struct {
name string
description string
}

// New creates a new preloadMemoryTool.
func New() *preloadMemoryTool {
return &preloadMemoryTool{
name: "preload_memory",
description: "Preloads relevant memory for the current user.",
}
}

// Name implements tool.Tool.
func (t *preloadMemoryTool) Name() string {
return t.name
}

// Description implements tool.Tool.
func (t *preloadMemoryTool) Description() string {
return t.description
}

// IsLongRunning implements tool.Tool.
func (t *preloadMemoryTool) IsLongRunning() bool {
return false
}

// ProcessRequest processes the LLM request by searching memory using the user's
// current query and injecting relevant past conversations into system instructions.
func (t *preloadMemoryTool) ProcessRequest(ctx tool.Context, req *model.LLMRequest) error {
userContent := ctx.UserContent()
if userContent == nil || len(userContent.Parts) == 0 ||
userContent.Parts[0] == nil || userContent.Parts[0].Text == "" {
return nil
}
userQuery := userContent.Parts[0].Text

searchResponse, err := ctx.SearchMemory(ctx, userQuery)
if err != nil {
return fmt.Errorf("preload memory search failed: %v", err)
}

if searchResponse == nil || len(searchResponse.Memories) == 0 {
return nil
}

memoryText := formatMemories(searchResponse.Memories)
if memoryText == "" {
return nil
}

utils.AppendInstructions(req, fmt.Sprintf(preloadInstructions, memoryText))
return nil
}

func formatMemories(memories []memory.Entry) string {
var lines []string
for _, mem := range memories {
memText := extractText(mem)
if memText == "" {
continue
}

if !mem.Timestamp.IsZero() {
lines = append(lines, fmt.Sprintf("Time: %s", mem.Timestamp.Format(time.RFC3339)))
}
if mem.Author != "" {
memText = fmt.Sprintf("%s: %s", mem.Author, memText)
}
lines = append(lines, memText)
}
return strings.Join(lines, "\n")
}

func extractText(mem memory.Entry) string {
if mem.Content == nil || len(mem.Content.Parts) == 0 {
return ""
}

var b strings.Builder
for _, part := range mem.Content.Parts {
if part.Text == "" {
continue
}
if b.Len() > 0 {
b.WriteByte(' ')
}
b.WriteString(part.Text)
}
return b.String()
}
219 changes: 219 additions & 0 deletions tool/preloadmemorytool/tool_test.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,219 @@
// Copyright 2026 Google LLC
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.

package preloadmemorytool_test

import (
"context"
"errors"
"strings"
"testing"
"time"

"google.golang.org/genai"

icontext "google.golang.org/adk/internal/context"
"google.golang.org/adk/internal/toolinternal"
"google.golang.org/adk/memory"
"google.golang.org/adk/model"
"google.golang.org/adk/session"
"google.golang.org/adk/tool"
"google.golang.org/adk/tool/preloadmemorytool"
)

type mockMemory struct {
memories []memory.Entry
err error
}

func (m *mockMemory) AddSession(ctx context.Context, s session.Session) error {
return nil
}

func (m *mockMemory) Search(ctx context.Context, query string) (*memory.SearchResponse, error) {
if m.err != nil {
return nil, m.err
}
return &memory.SearchResponse{Memories: m.memories}, nil
}

func TestPreloadMemoryTool_BasicProperties(t *testing.T) {
tool := preloadmemorytool.New()

if got := tool.Name(); got != "preload_memory" {
t.Errorf("Name() = %v, want preload_memory", got)
}
if got := tool.Description(); got != "Preloads relevant memory for the current user." {
t.Errorf("Description() = %v, want 'Preloads relevant memory for the current user.'", got)
}
if got := tool.IsLongRunning(); got != false {
t.Errorf("IsLongRunning() = %v, want false", got)
}
}

func TestPreloadMemoryTool_ProcessRequest(t *testing.T) {
tests := []struct {
name string
userContent *genai.Content
memories []memory.Entry
searchErr error
wantErr bool
wantInstruction bool
wantTextContains []string
}{
{
name: "nil user content",
userContent: nil,
wantInstruction: false,
},
{
name: "empty user content parts",
userContent: &genai.Content{Parts: []*genai.Part{}},
wantInstruction: false,
},
{
name: "user content with no text",
userContent: &genai.Content{Parts: []*genai.Part{{InlineData: &genai.Blob{}}}},
wantInstruction: false,
},
{
name: "text in later part is ignored",
userContent: &genai.Content{Parts: []*genai.Part{{InlineData: &genai.Blob{}}, genai.NewPartFromText("later text")}},
wantInstruction: false,
},
{
name: "no memories found",
userContent: genai.NewContentFromText("test query", genai.RoleUser),
memories: []memory.Entry{},
wantInstruction: false,
},
{
name: "memory search error",
userContent: genai.NewContentFromText("test query", genai.RoleUser),
searchErr: errors.New("search failed"),
wantErr: true,
wantInstruction: false,
},
{
name: "single memory entry",
userContent: genai.NewContentFromText("test query", genai.RoleUser),
memories: []memory.Entry{
{
Author: "user",
Timestamp: time.Date(2025, 1, 1, 12, 0, 0, 0, time.UTC),
Content: genai.NewContentFromText("Hello world", genai.RoleUser),
},
},
wantInstruction: true,
wantTextContains: []string{"PAST_CONVERSATIONS", "user: Hello world", "Time: " + time.Date(2025, 1, 1, 12, 0, 0, 0, time.UTC).Format(time.RFC3339)},
},
{
name: "multiple memory entries",
userContent: genai.NewContentFromText("search term", genai.RoleUser),
memories: []memory.Entry{
{
Author: "user",
Timestamp: time.Date(2025, 1, 1, 12, 0, 0, 0, time.UTC),
Content: genai.NewContentFromText("First memory", genai.RoleUser),
},
{
Author: "assistant",
Timestamp: time.Date(2025, 1, 2, 12, 0, 0, 0, time.UTC),
Content: genai.NewContentFromText("Second memory", genai.RoleModel),
},
},
wantInstruction: true,
wantTextContains: []string{"First memory", "Second memory", "user:", "assistant:"},
},
{
name: "memory entry without author",
userContent: genai.NewContentFromText("test", genai.RoleUser),
memories: []memory.Entry{
{
Timestamp: time.Date(2025, 1, 1, 12, 0, 0, 0, time.UTC),
Content: genai.NewContentFromText("Anonymous message", genai.RoleUser),
},
},
wantInstruction: true,
wantTextContains: []string{"Anonymous message"},
},
{
name: "memory entry without timestamp",
userContent: genai.NewContentFromText("test", genai.RoleUser),
memories: []memory.Entry{
{
Author: "user",
Content: genai.NewContentFromText("No timestamp", genai.RoleUser),
},
},
wantInstruction: true,
wantTextContains: []string{"user: No timestamp"},
},
{
name: "memory entry with empty content",
userContent: genai.NewContentFromText("test", genai.RoleUser),
memories: []memory.Entry{
{
Author: "user",
Timestamp: time.Date(2025, 1, 1, 12, 0, 0, 0, time.UTC),
Content: nil,
},
},
wantInstruction: false,
},
}

for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
tc := createToolContext(t, &mockMemory{memories: tt.memories, err: tt.searchErr}, tt.userContent)
llmRequest := &model.LLMRequest{}

pmt := preloadmemorytool.New()

err := pmt.ProcessRequest(tc, llmRequest)
if tt.wantErr {
if err == nil {
t.Fatalf("ProcessRequest expected error, got nil")
}
} else if err != nil {
t.Fatalf("ProcessRequest failed: %v", err)
}

hasInstruction := llmRequest.Config != nil && llmRequest.Config.SystemInstruction != nil
if hasInstruction != tt.wantInstruction {
t.Errorf("hasInstruction = %v, want %v", hasInstruction, tt.wantInstruction)
}

if tt.wantInstruction && hasInstruction {
instruction := llmRequest.Config.SystemInstruction.Parts[0].Text
for _, want := range tt.wantTextContains {
if !strings.Contains(instruction, want) {
t.Errorf("Instruction should contain %q, got: %v", want, instruction)
}
}
}
})
}
}

func createToolContext(t *testing.T, mem *mockMemory, userContent *genai.Content) tool.Context {
t.Helper()

ctx := icontext.NewInvocationContext(t.Context(), icontext.InvocationContextParams{
Memory: mem,
UserContent: userContent,
})

return toolinternal.NewToolContext(ctx, "", nil, nil)
}
Loading