Help us shape the future of Go! Take the 2026 Go Developer Survey

textsearch

package
v0.2.0 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Oct 20, 2026 License: MIT Imports: 12 Imported by: 0

Documentation

Overview

Package textsearch provides retrieval-augmented context from text searches.

Index

Examples

Constants

This section is empty.

Variables

This section is empty.

Functions

This section is empty.

Types

type Config

type Config struct {
	// SearchTime defaults to [BeforeInvoke].
	SearchTime SearchBehavior

	// FunctionToolName names the on-demand search tool. Nil defaults to "Search".
	FunctionToolName *string

	// FunctionToolDescription describes the on-demand search tool. Nil uses
	// "Allows searching for additional information to help answer the user question.".
	FunctionToolDescription *string

	// ContextPrompt prefixes search results. Nil uses a default additional-context prompt.
	// An explicit empty string suppresses the prompt text.
	ContextPrompt *string

	// CitationsPrompt follows search results. Nil uses a default citation instruction.
	// An explicit empty string suppresses the instruction text.
	CitationsPrompt *string

	// ContextFormatter replaces the default formatting and ignores both prompts.
	// Automatic searches do not call the formatter for an empty result list;
	// on-demand searches do. Formatting errors are ignored during automatic
	// searches, logged when Logger is configured, and returned from the on-demand tool.
	ContextFormatter func([]Result) (string, error)

	// RecentMessageMemoryLimit is the maximum number of individual messages
	// retained in the session and prepended to automatic search queries.
	// Zero disables memory. Negative values are invalid.
	RecentMessageMemoryLimit int

	// RecentMessageRolesIncluded selects message roles retained in memory.
	// Nil defaults to user messages; an empty, non-nil slice retains no messages.
	// Roles are compared case-insensitively. The slice is retained, not copied;
	// do not modify it while the provider is in use. This does not filter the
	// current request's search input.
	RecentMessageRolesIncluded []message.Role

	// StateKey identifies provider state in the session. Nil defaults to
	// "TextSearchProvider". Explicit empty or whitespace-only keys are invalid.
	// Use distinct keys for providers that need independent memory.
	StateKey *string

	// SearchInputMessageFilter filters automatic search input.
	// Nil defaults to [messagefilter.ExternalOnly].
	SearchInputMessageFilter messagefilter.Filter

	// StorageInputRequestMessageFilter filters request messages before storing memory.
	// Nil defaults to [messagefilter.ExternalOnly].
	StorageInputRequestMessageFilter messagefilter.Filter

	// StorageInputResponseMessageFilter filters response messages before storing memory.
	// Nil passes all response messages through.
	StorageInputResponseMessageFilter messagefilter.Filter

	// Logger receives provider diagnostics. When nil, no diagnostics are logged.
	Logger *slog.Logger

	// LogSensitiveData includes raw queries and formatted results in debug logs.
	// The default is false. When true, Redactor is ignored.
	LogSensitiveData bool

	// Redactor transforms queries and formatted results in debug logs.
	// When nil and LogSensitiveData is false, they are replaced with "<redacted>".
	Redactor func(string) string
}

Config configures the provider created by NewContextProvider.

type Provider

type Provider struct {
	// contains filtered or unexported fields
}

Provider supplies text search context and maintains optional recent-message memory in an agent.Session. Create it with NewContextProvider.

func NewContextProvider

func NewContextProvider(search func(context.Context, string) ([]Result, error), config Config) *Provider

NewContextProvider creates a text search context provider.

Attach it using agent.Config.ContextProviders. In automatic mode, filtered current request texts are joined with newlines, following any retained memory, and passed to search. Non-empty results are formatted and appended as a source-attributed user message. Search and formatting failures leave the input unchanged, including cancellation and deadline errors returned by search. Failures are logged only when Logger is configured. Message-filter and session-state errors are returned.

In on-demand mode, the provider adds a function tool accepting a userQuestion string. The tool searches only that query, without recent-message memory, and returns formatted text. Tool errors are returned to the tool-calling machinery. Use automatic tool invocation middleware when the provider does not execute tools.

Memory is stored after successful runs, in request-then-response order. Without a session, searches still work but no memory is retained. Automatic searches initialize session state even when memory retention is disabled.

Search inputs and retrieved documents are untrusted. The search implementation must enforce appropriate access controls, and retrieved content may require sanitization to prevent indirect prompt injection.

It panics if search is nil, RecentMessageMemoryLimit is negative, or StateKey is explicitly empty or whitespace-only.

Example
package main

import (
	"context"
	"fmt"

	"github.com/microsoft/agent-framework-go/agent"
	"github.com/microsoft/agent-framework-go/agent/textsearch"
	"github.com/microsoft/agent-framework-go/message"
)

func main() {
	provider := textsearch.NewContextProvider(func(_ context.Context, query string) ([]textsearch.Result, error) {
		return []textsearch.Result{{SourceName: "Guide", Text: "The answer is 42."}}, nil
	}, textsearch.Config{
		ContextFormatter: func(results []textsearch.Result) (string, error) { return results[0].Text, nil },
	})
	messages, _, err := provider.Invoking(context.Background(), agent.InvokingContext{
		Messages: []*message.Message{message.NewText("What is the answer?")},
	})
	if err != nil {
		panic(err)
	}
	fmt.Println(messages[len(messages)-1])
}
Output:
The answer is 42.

func (*Provider) Invoked

func (p *Provider) Invoked(ctx context.Context, invoked agent.InvokedContext) error

Invoked retains eligible request and response texts after successful runs.

func (*Provider) Invoking

func (p *Provider) Invoking(ctx context.Context, invoking agent.InvokingContext) ([]*message.Message, []agent.Option, error)

Invoking returns the original messages and options with search context or the on-demand search tool added.

func (*Provider) StateKeys

func (p *Provider) StateKeys() []string

StateKeys returns the session key used by this provider. The returned slice belongs to the caller.

type Result

type Result struct {
	SourceName string
	SourceLink string
	Text       string

	// RawRepresentation retains the underlying search result for a custom formatter.
	RawRepresentation any
}

Result contains a retrieved text chunk and its optional source information.

type SearchBehavior

type SearchBehavior int

SearchBehavior controls when a text search is executed.

const (
	// BeforeInvoke searches before each agent run and injects results as a user message.
	BeforeInvoke SearchBehavior = iota

	// OnDemandFunctionCalling exposes a search tool for the model to call when needed.
	OnDemandFunctionCalling
)

type State

type State struct {
	// RecentMessagesText contains retained message texts in chronological order.
	// Nil means memory has not been populated; a non-nil empty slice is stored
	// as an empty JSON array.
	RecentMessagesText []string `json:"recentMessagesText,omitzero"`
}

State is the provider's per-session state. The provider stores a *State under the key returned by Provider.StateKeys. Synchronize external edits with runs, and use agent.Session.Set to persist changes to restored state.

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL