azureprovider

package
v0.3.0 Latest Latest
Warning

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

Go to latest
Published: Nov 3, 2026 License: MIT Imports: 30 Imported by: 1 module, 0 packages

The first number is the count of modules that contain a package that imports this one. The module count is a better indicator of popularity than the package count. A module with 100 importing packages is counted only once instead of 100 times, reflecting the fact that the choice to use the package was likely made only once, not 100 times.
A '?' means that the value hasn't been computed yet.

README

Azure integrations

Azure AI Search indexes back typed and dynamic VectorData collections, including the chat-history memory provider.

search, err := azureprovider.NewAISearch(endpoint, azureprovider.AISearchConfig{
    Credential:         credential,
    EmbeddingGenerator: embedding.Bind(generator),
})
if err != nil {
    return err
}

collection, err := vectordata.GetCollection[uuid.UUID, *Document](
    search.Store, "documents", nil)
if err != nil {
    return err
}
if err := collection.EnsureExists(ctx); err != nil {
    return err
}

Here endpoint is https://<service>.search.windows.net, credential is an azcore.TokenCredential, and generator produces float32 embeddings. Set AISearchConfig.APIKey to azcore.NewKeyCredential(key) instead of Credential for API-key authentication. Azure Identity access to documents requires an appropriate data role; index creation also requires permission to manage indexes.

type Document struct {
    ID      uuid.UUID `vectordata:"key,storage=id"`
    Text    string    `vectordata:"data,indexed,fulltext,storage=text"`
    Content string    `vectordata:"vector,dimensions=3072,storage=vector"`
}

The example schema matches the default dimensions of text-embedding-3-large. An upsert stores Text as text and generates Content's vector. Generators run once per vector property for each batch; property and definition settings override the store default. Native float32 vectors need no generation.

  • Use search.DynamicCollection(name, definition) for map[string]any records. On Go 1.27, search.Collection[K, R](name, definition) is also available.
  • UUID keys are generated by default. Use pointer or map records to observe them on the input; disable generation through the key definition when needed.
  • Created indexes support filtering and sorting by the key field.
  • Storage names come from VectorData definitions and tags, not record json tags. Only schema properties are uploaded. Go int maps to Edm.Int64.
  • Nil collection fields, including native vectors, are uploaded as empty arrays without changing input records. Nullable scalar fields remain null.
  • HNSW and cosine similarity are defaults; flat indexes, dot product, and Euclidean distance are also supported.
  • String queries without a generator use Azure AI Search vectorization. This requires an existing index with a configured vectorizer; the connector does not provision vectorizers.
  • Vector fields are excluded from retrieval by default. Generated fields cannot be retrieved with IncludeVectors. Hybrid search supports full-text data fields. Score thresholds filter service-ranked candidates on the client.
  • Batch writes can partially succeed. All per-document failures are returned; generated input keys are not rolled back. Stores and collections do not close borrowed credentials, generators, or transports.

The connector uses the Azure azcore pipeline with REST API 2025-09-01. Behavior follows the pinned .NET connector.

See the runnable example.

Live validation

The integration tests create uniquely named indexes and delete only those indexes. They require permission to manage indexes and documents.

$env:RUN_AZURE_AI_SEARCH_INTEGRATION_TESTS = "true"
$env:AZURE_SUBSCRIPTION_ID = "<subscription ID>"
$env:AZURE_AI_SEARCH_ENDPOINT = "https://<service>.search.windows.net"
go test -count=1 .\provider\azureprovider -run "^TestE2E_AISearch"

Set AZURE_AI_SEARCH_API_KEY to test key authentication instead of Entra ID. Generated-vector and chat-history memory tests additionally use FOUNDRY_PROJECT_ENDPOINT and a FOUNDRY_EMBEDDING_MODEL deployment producing 3072-dimensional vectors (default text-embedding-3-large).

Cosmos DB chat history

Use CosmosHistoryProvider for persistent conversation history in Cosmos DB. See its Go doc comments for usage and configuration.

Documentation

Overview

Package azureprovider provides Azure service integrations.

Index

Constants

This section is empty.

Variables

This section is empty.

Functions

This section is empty.

Types

type AISearch

type AISearch struct {
	*vectordata.Store
}

AISearch manages Azure AI Search indexes through its embedded vectordata.Store. Create it with NewAISearch. Pass the embedded field to provider-independent APIs. Methods support concurrent use.

Keys are strings or uuid.UUID values. UUID keys are generated by default. Created indexes support filtering and sorting by the key field. Data fields support strings, booleans, signed integers, float32, float64, time.Time, nullable pointers to these types, and slices or arrays of scalars. Native vectors are []float32, embedding.VectorOf[float32], embedding.Of[float32], and *embedding.Of[float32]. Non-native vector fields require an embedding generator for upserts. String search inputs without a configured generator are sent to the index's server-side vectorizer.

Property storage names, including vectordata storage tags, define index field names. Record-level json tags do not override them. Only schema properties are uploaded. Nil collection fields are uploaded as empty arrays; nullable scalar fields remain null. Retrieval creates independent records and excludes vectors by default. IncludeVectors is unsupported for generated vector fields.

AISearch and its collections borrow credentials, generators, and transports and need no Close. Upserts and batch deletions can partially succeed; errors report failed documents. Generated keys are written to pointer and map inputs before upload. Plain structs are copied by value. Callers must not concurrently mutate inputs.

func NewAISearch

func NewAISearch(endpoint string, config AISearchConfig) (*AISearch, error)

NewAISearch creates a store for an Azure AI Search service endpoint, such as https://example.search.windows.net. It uses the 2025-09-01 REST API and the Azure SDK HTTP pipeline. Construction does not contact the service. Retry, logging, and transport settings use config.ClientOptions.

type AISearchConfig

type AISearchConfig struct {
	Credential azcore.TokenCredential
	APIKey     *azcore.KeyCredential

	// Audience is the token audience. Empty uses https://search.azure.com.
	Audience string

	// ClientOptions configures the Azure HTTP pipeline. Default transports and
	// supplied *http.Client values reject cross-origin redirects. Other custom
	// transports are responsible for their own redirect handling.
	ClientOptions azcore.ClientOptions

	// EmbeddingGenerator supplies the default generator for collections.
	// Definition and property generators take precedence.
	EmbeddingGenerator *embedding.BoundGenerator
}

AISearchConfig configures Azure AI Search. Set exactly one of Credential and APIKey.

type CosmosDB

type CosmosDB struct {
	*vectordata.Store
}

CosmosDB manages a Cosmos DB NoSQL database through its embedded vectordata.Store. Create it with NewCosmosDB.

A Cosmos DB client and database must already exist. The store borrows the client and embedding generator and does not close either. The caller remains responsible for closing the client.

Collections support string, uuid.UUID, and CosmosKey lookup keys. Record ID properties are strings or UUIDs. With the default partition path, string and UUID lookup keys identify both the document and its partition; custom and hierarchical paths require CosmosKey unless the only partition property is the document ID. UUID IDs are generated when the key property enables auto-generation.

Data properties support strings, booleans, signed integers, float32, float64, time.Time, nullable pointers to supported values, and slices or arrays of supported scalar values. Vector properties support float32, uint8, and int8 coordinates, including the corresponding embedding.VectorOf and embedding.Of types. Native vectors can be upserted directly; other vector properties require an embedding generator. Property and definition generators override the store default.

Stored timestamps and timestamp filter values use UTC RFC3339 strings with nine fractional-second digits, including nullable and collection values. Existing timestamps in other formats must be rewritten to this format for chronological ordering and range filters. Storage names with special characters are quoted as Cosmos DB path segments. The storage name "__cosmos_score" is reserved for search results.

Container policies include DiskANN, Flat, and QuantizedFlat vector indexes; DiskANN and cosine distance are defaults. Cosine, dot-product, and Euclidean distances are supported. Full-text indexing is available for string data properties with the en-US language policy. The account must have vector search enabled, and full-text queries require the corresponding account capability. Service constraints still apply; for example, small vector datasets may be scanned until an index can be built.

Search supports vector and full-text/vector hybrid queries with portable filters. The native Go client does not support cross-partition ranking or ordering: search and ordered retrieval require equality filters for every partition-key property, optionally nested in conjunctions. Unsupported queries return an error before calling the service or embedding generator. Choose partition paths that group records searched together; with the default /id path, ranked queries must filter to a single document ID. Unordered filtered retrieval supports cross-partition queries and applies Skip and top while paging. Queries project only schema properties, omitting vector fields unless IncludeVectors is true. Hybrid results are ranked with reciprocal-rank fusion and expose the raw vector distance as Score. Score thresholds compare against that distance (similarities use >=; Euclidean distance uses <=).

IncludeVectors is unsupported on collections with generated vector fields, including missing records and empty query results. Nil native vectors are stored as null; non-nil vectors must have the configured dimensions.

Item batches execute sequentially and may partially succeed. Generated input keys are not rolled back on failure. Per-collection partition and indexing settings are not available on the shared VectorData collection options; this provider configures those settings at store creation.

func NewCosmosDB

func NewCosmosDB(client *azcosmos.Client, databaseName string, config CosmosDBConfig) (*CosmosDB, error)

NewCosmosDB creates a store for databaseName using a caller-owned Cosmos DB client. The database must already exist; construction does not contact the service. The returned store borrows client and does not close it.

Create and configure the client separately, so applications control its authentication and transport:

client, err := azcosmos.NewClient(endpoint, credential, nil)
if err != nil {
    return err
}
defer client.Close()

store, err := azureprovider.NewCosmosDB(client, "vector-database", azureprovider.CosmosDBConfig{})
if err != nil {
    return err
}
collection, err := vectordata.GetCollection[string, Record](store.Store, "records", nil)

Use vectordata.Collection.EnsureExists to create the container and its indexing policies. It does not enable account-level vector or full-text search capabilities. The config's partition and indexing settings apply to all collections created from this store.

type CosmosDBConfig

type CosmosDBConfig struct {
	// PartitionKeyProperties lists record property names to use as the
	// collection's partition-key paths, in hierarchical order. An empty list
	// uses the document ID (/id), so collection keys must be string or
	// uuid.UUID. A non-empty list uses up to three key or scalar data
	// properties and requires [CosmosKey] for point operations unless the
	// only partition property is the document ID. Record ID properties remain
	// strings or uuid.UUID values, independently of the collection's lookup
	// key type. Supported partition values are strings, booleans, numbers,
	// uuid.UUID values, and null, including nullable pointers.
	// Property names refer to the VectorData schema, not serialized field
	// names; their storage names become Cosmos DB partition paths. The list
	// is copied when the store is created.
	PartitionKeyProperties []string

	// IndexingMode selects the indexing mode for newly created containers. It
	// accepts "consistent", "lazy", or "none", case-insensitively; the default
	// is "consistent". "none" omits vector and full-text index policies.
	IndexingMode string

	// Automatic controls automatic indexing for newly created containers. Nil
	// defaults to true; a pointer preserves an explicit false.
	Automatic *bool

	// EmbeddingGenerator supplies the default generator for vector properties
	// in this store. A collection definition or property-specific generator
	// takes precedence.
	EmbeddingGenerator *embedding.BoundGenerator
}

CosmosDBConfig configures container defaults shared by collections created from a Cosmos DB store. Create separate stores over the same client and database when different collections need different partition-key paths or indexing settings.

type CosmosHistoryProvider added in v0.3.0

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

CosmosHistoryProvider implements agent.HistoryProvider using a Cosmos DB NoSQL container. Create it with NewCosmosHistoryProvider. Documents use the "Message" type discriminator and message.Message JSON encoding. Caller messages and slices are not modified.

Messages are ordered by their stored Unix-second timestamp. Equal timestamps, including those in a write batch, have no guaranteed relative order or selection when a retrieval limit intersects a tie. Transactional batches are atomic individually, not across a complete write or clear operation. Failures are returned; earlier batches may have committed. Oversized write batches split and retry; individually oversized messages return an error preserving the SDK cause. Throttling retries follow the configured SDK policy.

Stored messages can contain sensitive data. Configure appropriate access controls, encryption, network security, and retention. Retrieved messages are trusted as conversation history without additional validation or sanitization.

A provider can be shared across sessions. Callers must synchronize edits to session state with operations. Do not copy a provider after use.

func NewCosmosHistoryProvider added in v0.3.0

func NewCosmosHistoryProvider(client *azcosmos.Client, databaseID, containerID string, stateInitializer func(*agent.Session) *CosmosHistoryState, config CosmosHistoryProviderConfig) (*CosmosHistoryProvider, error)

NewCosmosHistoryProvider creates a provider for an existing database and container. Construction does not contact the service. Attach the provider through agent.Config.HistoryProvider.

Configure authentication, transport, and retries using azcosmos.NewClient, azcosmos.NewClientWithKey, or azcosmos.NewClientFromConnectionString. The client is borrowed unless config.OwnsClient is true. Close the provider when finished; closing a borrowing provider does not close the client.

stateInitializer is required and supplies routing state on first use of a session. It must return a non-nil state with a nonblank ConversationID. State is retained in the session and survives JSON serialization. Without a session, the initializer is called with nil for each operation and no state is retained. It must return stable routing information for operations to share history. Configuration values are captured at construction.

For example, with a caller-owned client:

history, err := azureprovider.NewCosmosHistoryProvider(client, "agents", "history",
	func(*agent.Session) *azureprovider.CosmosHistoryState {
		return &azureprovider.CosmosHistoryState{ConversationID: uuid.NewString()}
	}, azureprovider.CosmosHistoryProviderConfig{})
if err != nil {
	return err
}
defer history.Close()
a := agent.New(providerConfig, agent.Config{HistoryProvider: history})

func (*CosmosHistoryProvider) ClearMessages added in v0.3.0

func (p *CosmosHistoryProvider) ClearMessages(ctx context.Context, session *agent.Session) (int, error)

ClearMessages deletes all chat-message documents in the conversation, independently of retrieval limits and filters. It returns the number of successfully deleted documents, including on an error after partial progress. It retains the conversation's session state.

func (*CosmosHistoryProvider) Close added in v0.3.0

func (p *CosmosHistoryProvider) Close() error

Close prevents further storage operations and closes the client if OwnsClient was set. It is idempotent and does not cancel operations already in flight.

func (*CosmosHistoryProvider) ContainerID added in v0.3.0

func (p *CosmosHistoryProvider) ContainerID() string

ContainerID returns the configured container ID.

func (*CosmosHistoryProvider) DatabaseID added in v0.3.0

func (p *CosmosHistoryProvider) DatabaseID() string

DatabaseID returns the configured database ID.

func (*CosmosHistoryProvider) Invoked added in v0.3.0

Invoked stores filtered request messages followed by response messages. Failed runs are not stored.

func (*CosmosHistoryProvider) Invoking added in v0.3.0

Invoking prepends source-attributed, filtered history to the input messages.

func (*CosmosHistoryProvider) MessageCount added in v0.3.0

func (p *CosmosHistoryProvider) MessageCount(ctx context.Context, session *agent.Session) (int, error)

MessageCount counts all chat-message documents in the conversation, independently of retrieval limits and message filters.

func (*CosmosHistoryProvider) Messages added in v0.3.0

func (p *CosmosHistoryProvider) Messages(ctx context.Context, session *agent.Session) ([]*message.Message, error)

Messages retrieves stored messages in timestamp order, applying MaxMessagesToRetrieve but not the invocation output filter or source attribution.

func (*CosmosHistoryProvider) StateKeys added in v0.3.0

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

StateKeys returns the session state key. The returned slice belongs to the caller.

type CosmosHistoryProviderConfig added in v0.3.0

type CosmosHistoryProviderConfig struct {
	// OwnsClient transfers responsibility for closing the supplied client to the
	// provider. The default is false.
	OwnsClient bool

	// StateKey identifies provider state in the session. Nil defaults to
	// "CosmosHistoryProvider". Empty and whitespace-only keys are invalid.
	// Use distinct keys for independent providers sharing a session.
	StateKey *string

	// MaxItemCount limits query page sizes. Nil defaults to 100. An explicit
	// value must be positive, or -1 for a service-selected page size.
	MaxItemCount *int32

	// MaxBatchSize limits operations in each transactional batch. Nil defaults
	// to 100. Explicit values must be between 1 and 100.
	MaxBatchSize *int

	// MaxMessagesToRetrieve limits retrieval to the most recent messages. Nil
	// retrieves all messages. Zero retrieves none; negative values are invalid.
	// This limit does not affect [CosmosHistoryProvider.MessageCount] or
	// [CosmosHistoryProvider.ClearMessages].
	MaxMessagesToRetrieve *int

	// MessageTTLSeconds sets the per-item expiration in seconds. Nil defaults
	// to 86400 (24 hours). Zero omits ttl, allowing the container default to
	// apply. -1 disables item expiration. Other negative values are invalid.
	// The container must have TTL enabled for expiration to take effect.
	MessageTTLSeconds *int32

	// PartitionKeyFactory overrides the default routing described by
	// [CosmosHistoryState] for retrieval, storage, count, and deletion. It
	// must return a key matching the container definition and stored document
	// values. The state and its pointed-to values are read-only.
	PartitionKeyFactory func(CosmosHistoryState) azcosmos.PartitionKey

	// ProvideOutputMessageFilter filters retrieved messages during
	// [CosmosHistoryProvider.Invoking]. Nil passes all retrieved messages
	// through. [CosmosHistoryProvider.Messages] bypasses this filter.
	ProvideOutputMessageFilter messagefilter.Filter

	// StoreInputRequestMessageFilter filters request messages before storage.
	// Nil excludes messages supplied by history providers.
	StoreInputRequestMessageFilter messagefilter.Filter

	// StoreInputResponseMessageFilter filters response messages before storage.
	// Nil stores all response messages.
	StoreInputResponseMessageFilter messagefilter.Filter
}

CosmosHistoryProviderConfig configures NewCosmosHistoryProvider.

type CosmosHistoryState added in v0.3.0

type CosmosHistoryState struct {
	ConversationID string  `json:"conversationId"`
	TenantID       *string `json:"tenantId,omitempty"`
	UserID         *string `json:"userId,omitempty"`
}

CosmosHistoryState identifies a conversation in Cosmos DB. ConversationID must be nonblank. The default container partition path is /conversationId. When both TenantID and UserID are non-nil, the container must instead use hierarchical paths /tenantId, /userId, and /sessionId, in that order. Non-nil empty tenant and user IDs remain key components. Documents always store ConversationID as sessionId and retain supplied tenant and user metadata, regardless of partition strategy.

The provider stores a *CosmosHistoryState in the session under its CosmosHistoryProvider.StateKeys key. Synchronize changes with operations and use agent.Session.Set to persist edits to restored state. Partition keys route data; they do not replace application-level authorization.

type CosmosKey

type CosmosKey struct {
	DocumentID   string
	PartitionKey []any
}

CosmosKey identifies a Cosmos DB document and its scalar or hierarchical partition key components when a collection uses custom partition paths. DocumentID must be nonblank. PartitionKey must contain one to three values matching CosmosDBConfig.PartitionKeyProperties in order. Components may be strings, booleans, numbers, uuid.UUID values, or nil; UUIDs are sent as strings. The record's key property stores only the document ID as a string or UUID, not a CosmosKey. Use a plain string or uuid.UUID lookup key when the collection uses the default /id partition path.

Jump to

Keyboard shortcuts

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