extensions 0.7.0
extensions: ^0.7.0 copied to clipboard
A set of APIs for commonly used programming patterns and utilities, such as dependency injection, logging, and configuration.
0.7.0 #
- AI — chat routing (new; upstream marks this family
[Experimental]):- Added
RoutingChatClient, a template base that selects and invokes another chat client per request, with aRoutingChatClient.fromSelectorfactory, plusRoutingContext. - Added
FailoverChatClientandFailoverChatClientAttempt: after a failed invocation another client can be selected, but only while the failure is uncanceled, happened before any streaming output was exposed, andmaximumAttemptsPerRequestpermits it. Attempts carry an explicitstackTraceso policies can rethrow without losing the original stack. - Added
OrderedFailoverChatClient(tries clients in order, rethrows the final failure when all fail) andSemanticRoutingChatClient(routes by cosine similarity between the last user message and example-utterance profiles, withSemanticRoutingScoreAggregationand a score-threshold fallback to a default client).
- Added
- AI — new members on existing types:
UsageDetailsgainedinputAudioTokenCount,inputTextTokenCount,outputAudioTokenCount, andoutputTextTokenCount, all merged byadd().AIFunction.asDeclarationOnly()returns a declaration-only view of a function that describes it but cannot be invoked.List<ChatMessage>gainedaddMessagesFromResponse,addMessagesFromUpdates,addMessagesFromUpdate(with an optional content filter), andaddMessagesFromStreamfor appending response messages to a conversation history.
- AI — shared function-invocation engine:
FunctionInvokingChatClientandFunctionInvokingRealtimeClientSessionnow share one internal invocation processor (the upstreamCommon/refactor). Function executions emitexecute_toolspans throughdart:developer'sTimeline, and invocation log messages follow upstream wording and levels (unknown functions now log at warning; invocations log at debug, with arguments and results at trace).- Behavioral refinements from upstream: declaration-only tools are reported back to the model as not found instead of silently matching nothing, serial invocation stops after a result that requests termination, and cancellation now propagates instead of being captured as a function failure.
0.6.0 #
-
BREAKING — AI function invocation now matches upstream loop limits:
- Reaching
maximumIterationsPerRequestno longer returns a response with unanswered tool calls. Following upstream, the final request omits function declarations fromChatOptions.tools(non-function tools and, when any remain,toolModeare preserved) so the model produces a real answer. If it requests a call anyway, that response is returned without invoking anything. Note that this tool-free request is a real round trip, so a request that reaches the limit now makes one more provider call than before. - Exceeding
maximumConsecutiveErrorsPerRequestnow throws instead of silently returning a partial response. A single failure is rethrown as-is so callers can catch the tool's own error type; multiple failures are combined into anAggregateException, which is now also exported frompackage:extensions/ai.dart. - The limit comparison was
>=and is now>, matching upstream: a limit of n tolerates n consecutive failing iterations. A limit of0therefore surfaces the first tool failure immediately.
- Reaching
-
AI — provider annotations:
AIContentgained anannotationsfield carrying provider-returned citations (AIAnnotation/CitationAnnotation).
-
AI — OpenTelemetry coverage completed:
- Added
OpenTelemetrySpeechToTextClient,OpenTelemetryHostedFileClient, andOpenTelemetryRealtimeClient(plus its session decorator), each with a matching builder extension. - Instrumentation is spans-only, emitted through
dart:developer'sTimeline. Because the port avoidsdart:io, the upstreamOTEL_INSTRUMENTATION_GENAI_CAPTURE_MESSAGE_CONTENTenvironment variable has no counterpart — hosts setTelemetryHelpers.enableSensitiveDataDefaultat bootstrap instead.
- Added
-
HTTP — handler lifetime management:
HttpMessageHandlerinstances are now disposed only after in-flight requests complete, tracked by active/expired handler entries and a timer-driven cleanup cycle. The implementation is web-safe and uses no finalizers.HttpClientBuildergainedaddAsKeyed,removeAsKeyed, andconfigureAdditionalHttpMessageHandlers.
0.5.0 #
- VectorData — interfaces renamed to Dart conventions:
IVectorSearchable→VectorSearchableandIKeywordHybridSearchable→KeywordHybridSearchable. The old names remain as deprecated typedefs.
- BREAKING — FileSystemGlobbing rewritten as a faithful upstream port:
Matchernow uses a full port of the upstream pattern engine (literal, linear, and ragged patterns with pattern contexts) instead of delegating topackage:glob.package:glob'sGlobis no longer re-exported frompackage:extensions/file_system_globbing.dart. Code that relied on the re-export must importpackage:glob/glob.dartdirectly.- Pattern syntax now follows upstream semantics: exact names,
*within a name segment,**across directory levels, a leading..for the parent directory, and a trailing/treated asdir/**. The glob-specific?,[abc], and{a,b}forms are no longer supported. - New
Matcherconstructor parameters:comparisonType(StringComparison.ordinalorordinalIgnoreCase, matching upstream case-insensitive default) andpreserveFilterOrder(applies filters in the order added so a later include can re-admit an excluded file). matchFile/matchFilesnow run through the real matcher against an in-memory tree built by the newInMemoryDirectoryInfo.fromPaths, so in-memory results agree with disk-based matching.getResultsInFullPathnow returns normalized paths.- Fixed the
PatternMatchingResult.filessetter, which previously assigned the field to itself.
- AI — chat client structured output:
- Added
ChatClient.getStructuredResponse<T>()andStructuredChatResponse<T>for requesting JSON responses that deserialize into a typed result, with support for schema injection, wrapped-object envelopes, and native JSON response formats.
- Added
- AI — distributed caching:
- Added
DistributedCachingChatClientandChatClientBuilder.useDistributedCache(). - Added
CachingEmbeddingGenerator,DistributedCachingEmbeddingGenerator, andEmbeddingGeneratorBuilder.useDistributedCache().
- Added
- AI — builder pipeline glue:
ChatClientBuildergaineduseConfigureOptions,useChatReducer, anduseImageGenerationextensions.EmbeddingGeneratorBuilder,ImageGeneratorBuilder,TextToSpeechClientBuilder,SpeechToTextClientBuilder, andHostedFileClientBuildergaineduseLoggingand (where applicable)useConfigureOptionsextensions,asBuilder()on the corresponding client/generator types, andServiceCollectionregistration extensions (addEmbeddingGenerator,addImageGenerator,addTextToSpeechClient,addSpeechToTextClient).
- AI — chat response accumulation:
- Added public
toChatResponse()extensions onIterable<ChatResponseUpdate>andStream<ChatResponseUpdate>plus aChatResponseAccumulator, replacing the private accumulation logic inChatClientBuilder.
- Added public
- AI —
DataContent:DataContent.fromUrinow parsesdata:URIs sodataandmediaTypeare populated from the URI contents, and throwsFormatExceptionon malformed data URIs.- The
urigetter now synthesizes a data URI fromdataandmediaTypewhen the content was created from raw bytes.
0.4.1 #
- Web-compatible file configuration:
- File-based JSON configuration is now available from
package:extensions/configuration.dartand can read from an injectedFileProvider, including memory-backed providers on web. - Added a web-safe
FileSystemExceptionstand-in for file configuration errors.
- File-based JSON configuration is now available from
- File providers and globbing:
PhysicalFileProvidernow supports injectedpackage:filefilesystems, allowing in-memory filesystem use in browser and test environments.- Polling change tokens, wildcard watching, and
Matcherglobbing now work through filesystem abstractions instead of directdart:ioaccess. - Resolved a
FileSystemExceptionexport ambiguity in the aggregatepackage:extensions/extensions.dartbarrel.
0.4.0 #
- Web compatibility:
package:extensions/configuration.dart,hosting.dart, andlogging.dartare now web-safe and can be compiled to JavaScript. Console logging falls back toprintand disables ANSI colors on web, and the defaultHostApplicationBuilderskips file-backed configuration and environment variables on web.package:extensions_flutter/extensions_flutter.dartis now web-compatible as a result.
- BREAKING — JSON file configuration moved to
configuration_io.dart:addJsonis no longer exported frompackage:extensions/configuration.dartbecause it depends ondart:io. It now lives inpackage:extensions/configuration_io.dart(also re-exported fromio.dartand the aggregatepackage:extensions/extensions.dart).- Migration: code that imports
configuration.dartdirectly and callsaddJsonmust addimport 'package:extensions/configuration_io.dart';. Code importingpackage:extensions/extensions.dartis unaffected.
- Dependencies:
- Added
universal_platformfor web-safe platform detection in the console log formatter.
- Added
0.3.28 #
-
AI Realtime — Function invocation:
- Added experimental
FunctionInvokingRealtimeClient,FunctionInvokingRealtimeClientSession, andRealtimeClientBuilder.useFunctionInvocation()for automatically invokingAIFunctiontools requested by realtime model responses. - Function results are sent back to the realtime session as conversation items and the model is prompted to continue the response.
- Added controls for detailed errors, concurrent invocation, iteration/error limits, additional tools, and unknown-function handling.
- Added experimental
-
AI — Bug fix:
EmptyServiceProvidernow behaves as an empty provider instead of throwingUnimplementedErrorfor optional service lookups.
-
HTTP — Cleanup:
- Removed a duplicate
@overrideannotation inDefaultHttpClientFactory.createClient.
- Removed a duplicate
0.3.27 #
- Hosting —
BackgroundService/Hostlifecycle fixes:Host.startAsyncno longer awaits aBackgroundService'sexecuteoperation, so startup completes oncestartreturns instead of blocking on long-running services (mirrors C#StartAsyncsemantics).BackgroundService.stopnow mirrors C#Task.WhenAnyby waiting for the execute operation to complete without observing its error or cancellation, so stopping a faulted or cancelled service no longer rethrows.Hosttreats anOperationCanceledExceptionfrom a background service during shutdown as a normal stop rather than logging it as a fault.BackgroundService.disposeis now null-safe when the service was never started.
0.3.26 #
- AI — OpenAI provider:
OpenAIChatClientnow honoursChatOptions.rawRepresentationFactory: if the factory returns aMap<String, dynamic>, its entries are merged into the HTTP request body before the request is sent, providing an escape hatch for provider-specific parameters not covered byChatOptions.
0.3.25 #
- AI — OpenAI provider:
- Added
OpenAIChatClient— aChatClientimplementation for the OpenAI chat completions API (POST /chat/completions). Supports streaming (SSE), tool calls, response format control (text,json_object,json_schema), and allChatOptionsfields. ConfiguringOpenAIClientOptions.endpointto a local server (e.g.http://localhost:1234/v1) makes it compatible with LM Studio, Ollama, and other OpenAI-compatible servers. - Added
OpenAIEmbeddingGenerator— anEmbeddingGenerator<String, float>for the OpenAI embeddings API, with optionaldimensionsanddefaultModelDimensionssupport. - Added
OpenAIImageGenerator— anImageGeneratorfor DALL-E andgpt-image-1, returningDataContent(base-64) orUriContent(URL). - Added
OpenAISpeechToTextClient— aSpeechToTextClientbacked by the Whisper transcription and translation endpoints via multipart upload. - Added
OpenAITextToSpeechClient— aTextToSpeechClientwith both non-streaming and streaming audio delivery. - Added
OpenAIClientOptions— holdsendpointURI (default:https://api.openai.com/v1) and an injectablehttp.Clientfor testing. - Added
OpenAIServiceCollectionExtensions— DI convenience methods (addOpenAIChatClient,addOpenAIEmbeddingGenerator, etc.) onServiceCollection. - Added
LoggingChatClientBuilderExtensions.useLogging()— integratesLoggingChatClientinto aChatClientBuilderpipeline, skipping the logging step when the resolved factory isNullLoggerFactory.
- Added
0.3.24 #
-
VectorData — expanded abstractions:
- Added annotation types:
VectorStoreDataAttribute,VectorStoreKeyAttribute,VectorStoreVectorAttributefor decorating record classes (intended for code generators or explicit schema construction). - Added
DistanceFunctionandIndexKindstring-constant classes for use in vector property configuration. - Added full
VectorStoreCollectionDefinitionrecord schema withVectorStoreProperty,VectorStoreKeyProperty,VectorStoreDataProperty, andVectorStoreVectorProperty. - Added
VectorSearchOptions,VectorSearchResult<TRecord>, andRecordRetrievalOptions. - Added
FilteredRecordRetrievalOptions<TRecord>for filtered, ordered, paginated record retrieval, withOrderByClause.ascending/OrderByClause.descendinghelpers. - Added
HybridSearchOptionsfor keyword + vector hybrid search. - Added
IVectorSearchable<TRecord>andIKeywordHybridSearchable<TRecord>interfaces. - Added deprecated legacy filter clause hierarchy (
FilterClause,EqualToFilterClause,AnyTagEqualToFilterClause) for compatibility with code targeting the old C# API surface; preferVectorStoreFilterand its sealed subclasses.
- Added annotation types:
-
AI — Bug fix:
- Added
namefield toFunctionResultContent;FunctionInvokingChatClientnow populates it so providers can correlate results back to the originating function declaration.
- Added
-
Logging — Cleanup:
- Renamed
ILoggerProviderConfiguration<T>toLoggerProviderConfiguration<T>— theI-prefixed name and its typedef alias have been removed. Update any direct references to the abstract class.
- Renamed
-
Dependency Injection — Bug fix:
- Fixed
getRequiredServiceerror message: was printingType.runtimeType(always"Type") instead of the actual type name.
- Fixed
-
System — Bug fix:
ExceptionBase.toString()now returns"TypeName: message"instead of the defaultInstance of 'TypeName'.
0.3.23 #
- Fixed missing
export 'ai.dart'in theextensions.dartbarrel file.
0.3.22 #
-
AI — Microsoft.Extensions.AI port (Phases 1–4):
-
Phase 1 — Core API gaps:
- Added
ReasoningOptions,ReasoningEffort, andReasoningOutputtypes for model reasoning control - Added
allowBackgroundResponsesandrawRepresentationFactorytoChatOptions - Replaced merged content types with proper call/result pairs:
CodeInterpreterToolCallContent/CodeInterpreterToolResultContent,ImageGenerationToolCallContent/ImageGenerationToolResultContent,McpServerToolCallContent/McpServerToolResultContent,InputRequestContent/InputResponseContent,WebSearchToolCallContent/WebSearchToolResultContent - Added abstract
ToolCallContentandToolResultContentbase classes - Added
ToolApprovalRequestContent/ToolApprovalResponseContentfor user-in-the-loop approval flows - Added
AIFunctionDeclaration,AIFunctionFactoryOptions,DelegatingAIFunctionDeclaration,ApprovalRequiredAIFunction - Added
HostedToolSearchToolandHostedMcpServerToolapproval mode hierarchy (AlwaysRequire,NeverRequire,RequireSpecific) - Added
AIContentExtensionswithfirstOfType<T>()andallOfType<T>()helpers - Added
AutoChatToolModeto the public API
- Added
-
Phase 2 — New client types:
- Added
TextToSpeechClientpipeline:TextToSpeechClient,TextToSpeechOptions,TextToSpeechResponse,TextToSpeechResponseUpdate,TextToSpeechClientMetadata,DelegatingTextToSpeechClient,ConfigureOptionsTextToSpeechClient,LoggingTextToSpeechClient,TextToSpeechClientBuilder - Added
HostedFileClientpipeline:HostedFileClient,DelegatingHostedFileClient,LoggingHostedFileClient,HostedFileClientBuilder
- Added
-
Phase 3 — OpenTelemetry middleware:
- Added
OpenTelemetryChatClient,OpenTelemetryEmbeddingGenerator,OpenTelemetryImageGenerator,OpenTelemetryTextToSpeechClientdecorators - Added
useOpenTelemetry()builder extension for each client type - Added
OpenTelemetryConstswith span and attribute name constants
- Added
-
Phase 4 — Evaluation framework:
- NLP evaluators:
BleuEvaluator,F1Evaluator,GleuEvaluatorwith supporting algorithms (BleuAlgorithm,F1Algorithm,GleuAlgorithm,NGram,SimpleWordTokenizer) - Quality evaluators:
CoherenceEvaluator,CompletenessEvaluator,EquivalenceEvaluator,FluencyEvaluator,GroundednessEvaluator,IntentResolutionEvaluator,RelevanceTruthAndCompletenessEvaluator,RetrievalEvaluator,TaskAdherenceEvaluator,ToolCallAccuracyEvaluator - Safety evaluators:
CodeVulnerabilityEvaluator,ContentHarmEvaluator,HateAndUnfairnessEvaluator,IndirectAttackEvaluator,ProtectedMaterialEvaluator,SelfHarmEvaluator,SexualEvaluator,ViolenceEvaluator,UngroundedAttributesEvaluator,GroundednessProEvaluator - Reporting:
ScenarioRun,ReportingConfiguration,ResponseCachingChatClient, disk-basedResponseCache,ResultStore, andReportingConfigurationfactory
- NLP evaluators:
-
-
VectorData — Microsoft.Extensions.VectorData.Abstractions port:
- Added
VectorStore,VectorStoreCollection<TKey, TRecord>, andVectorStoreRecordCollection<TKey, TRecord>abstractions - Added
VectorStoreFiltersealed hierarchy:EqualToVectorStoreFilter,AnyTagEqualToVectorStoreFilter,AndVectorStoreFilter,OrVectorStoreFilter - Added record definition types:
VectorStoreRecordDefinition,VectorStoreRecordDataProperty,VectorStoreRecordKeyProperty,VectorStoreRecordVectorProperty - Added attribute annotations:
VectorStoreRecordData,VectorStoreRecordKey,VectorStoreRecordVector - Added options types for all collection operations with distinct method names (
getAsync/getBatchAsync/getFilteredAsync,upsertAsync/upsertBatchAsync,deleteAsync/deleteBatchAsync) - Added
OrderByClausewithascending(field)/descending(field)factory methods - Exported from
package:extensions/vector_data.dartand included inpackage:extensions/extensions.dart
- Added
-
Bug Fix — Dependency Injection:
- Fixed
getKeyedServices<T>(key)always returning empty or throwing aTypeError. The method now correctly requestsIterable<T>from the provider (mirroring the non-keyedgetServices<T>()and the C#GetKeyedServices<T>()implementation), which routes throughCallSiteFactory.tryCreateIterable()and aggregates all registrations under the given key. getKeyedServicesFromType(Type, key)now throwsUnsupportedErrorwith a clear message (Dart cannot constructIterable<T>from a runtimeType; usegetKeyedServices<T>()instead).
- Fixed
0.3.21 #
- Updates.
0.3.20 #
- Updates.
0.3.19 #
- Code Quality:
- Improved export visibility in hosting libraries by hiding internal implementation functions (
addCommandLineConfig,addDefaultServices,applyDefaultAppConfiguration,createDefaultServiceProviderOptions) - Code formatting improvements in AI logging clients (line length fixes)
- Improved import naming conventions in
HostApplicationBuilderto follow Dart style guidelines - Fixed documentation reference in
FunctionInvocationContext
- Improved export visibility in hosting libraries by hiding internal implementation functions (
0.3.18 #
-
Bug Fixes:
- Fixed
PhysicalFileProvider.getFileInfo()andgetDirectoryContents()incorrectly handling nested directory paths by removing the first path separator anywhere in the path instead of only at the beginning - Fixed
LoggerFactory.addProvider()throwingRangeErrorwhen adding providers after loggers were already created due to incorrect list index assignment - Improved
_isUnderneathRoot()validation to prevent false positive matches on paths with common prefixes - Fixed file polling tests to account for file system timestamp granularity (1-second precision)
- Fixed
-
Code Quality:
- Fixed all analyzer issues (import ordering, naming conventions, line length, unused imports/variables)
- Renamed
ArgumentOutOfRangeException.ThrowNegative()andThrowNegativeOrZero()to follow Dart naming conventions (lowerCamelCase) - Improved test reliability by ensuring proper timing for file system timestamp changes
- Disabled
cascade_invocationslint rule to reduce noise in test files
-
Test Improvements:
- Fixed and re-enabled 3 previously skipped tests
- All 508 tests now pass with improved timing reliability
- Added better handling for platform-specific file system behavior
0.3.17 #
- Bug fixes and improvements.
0.3.16 #
-
Major Feature Additions:
- Added comprehensive Caching module with in-memory and distributed cache support
- Added HTTP Client Logging with configurable formatters and redaction
- Added high-performance LoggerMessage API for zero-allocation logging
- Added Typed Logger support (
Logger<T>) - Added advanced Console Formatters (Simple, JSON, Systemd)
- Added File System Globbing with advanced pattern matching
- Added Diagnostics module for activity tracking and metrics
-
Caching:
- New
MemoryCachewith size limits, priorities, and eviction policies DistributedCacheabstraction with in-memory implementation- Post-eviction callbacks and cache statistics
- Sliding and absolute expiration support
- Examples: example_caching.dart
- New
-
Logging:
- High-performance
LoggerMessage.defineAPI for cached log delegates BufferedLogRecordfor structured logging scenariosNullTypedLogger<T>for testing and no-op scenarios- Console formatters with customizable output (simple, JSON, systemd)
- Color support and timestamp formatting
- Examples: example_advanced_logging.dart, example_console_formatters.dart
- High-performance
-
HTTP:
- HTTP client logging with request/response tracking
- Header redaction for sensitive data
- Configurable handler lifetime
- Scoped logging integration
- Example: example_http_client_logging.dart
-
File Providers:
- Enhanced polling change tokens with debouncing
- Physical file provider options
- Improved file watching reliability
- Example: example_file_providers.dart
-
File System Globbing:
- Advanced pattern matching with multiple patterns
- Exclusion support
- Case-sensitive/insensitive matching
- Example: example_file_system_globbing.dart
-
Diagnostics:
- Activity tracking and propagation
- Diagnostic listeners
- Example: example_diagnostics.dart
-
Testing:
- Added 1000+ new test cases across all modules
- Comprehensive test coverage for caching, logging, and primitives
-
Code Quality:
- Fixed all analyzer warnings and errors
- Improved type inference in examples
- Removed unused imports and variables
-
Breaking Changes:
- None - all additions are backward compatible
0.3.15 #
- Changed logging scope for lifetime messages and added additional tests.
0.3.14 #
- Updates.
0.3.13 #
- Bug fixes.
0.3.12 #
- Updates.
0.3.11 #
- Exported CancellationTokenRegistration.
0.3.10 #
- Added const constructor to NullLoggerFactory.
0.3.9 #
- Exported NullLogger, NullLoggerFactory, and CancellationTokenSource. Changed Logger.logError to not require and exception.
0.3.8 #
- Bug fixes and updates.
0.3.7 #
- Bug fixes and updates.
0.3.6 #
- Downgrading
asyncpackage.
0.3.5 #
- Bug fixes and updates.
0.3.4 #
- Bug fixes and updates.
0.3.3 #
- Bug fixes and updates.
0.3.2 #
- Bug fixes and updates.
0.3.1 #
- Bug fixes and updates.
0.3.0 #
- Initial version