AI SDK
- Installation and Configuration
- Laravel-style API
- Providers
- Agents
- Conversations
- Attachments
- Agent Middleware
- Structured Output and Classification
- Tools and MCP
- Streaming
- Images, Audio, and Retrieval
- Files and Vector Stores
- Vector Search
- Queues and Broadcasting
- Retries, Failover, and Usage
- Events
- Testing
- Complete Example: Authenticated Assistant
- Complete Offline Self-Check
Installation and Configuration
DotBlaze.AI is an optional package targeting .NET 10. Its fluent API follows the Laravel AI SDK, using C# method names, Task/await, and Microsoft.Extensions.AI chat and tool types.
The built-in OpenAI, OpenAI-compatible, Anthropic, and Gemini chat gateways make HTTP requests directly. Microsoft.Extensions.AI supplies the common types and tool-invocation loop; no OpenAI SDK dependency is required.
dotnet add package DotBlaze.AI
dotblaze migrateDotBlaze discovers the package's service provider and conversation migration automatically. Generation without stored conversations does not need the database tables.
Use DotBlaze for the Ai facade, DotBlaze.ArtificialIntelligence for the AI classes, and Microsoft.Extensions.AI for chat/tool types. Constructor injection is supported through IAi and IConversationStore.
using DotBlaze;
using DotBlaze.ArtificialIntelligence;
using Microsoft.Extensions.AI;
using Image = DotBlaze.ArtificialIntelligence.Image;The Image alias distinguishes AI generation from the raster-processing DotBlaze.Image class when both optional packages are installed.
Publish the editable configuration (optional; runtime defaults work without it):
dotblaze vendor:publish --provider=DotBlaze.ArtificialIntelligence.AiServiceProvider
# Equivalent: dotblaze vendor:publish --tag=ai-config
dotnet buildThis creates config/Ai.cs with your application's namespace and environment-variable references for keys. Existing files are preserved unless --force is passed. See Publishing Resources for package and tag filters.
The published template is minimal; expand it as needed, for example:
using DotBlaze;
namespace App.Configuration;
public class AiConfig : ConfigFile
{
public override object Values() => new
{
@default = "openai",
defaults = new { reranking = "cohere" },
conversations = new
{
tables = new
{
conversations = "agent_conversations",
messages = "agent_conversation_messages",
},
},
providers = new
{
openai = new
{
driver = "openai",
key = Env("OPENAI_API_KEY"),
models = new
{
text = "gpt-4.1-mini",
images = "gpt-image-2",
audio = "gpt-4o-mini-tts",
transcription = "whisper-1",
embeddings = "text-embedding-3-small",
},
},
cohere = new { driver = "cohere", key = Env("COHERE_API_KEY") },
voyage = new { driver = "voyageai", key = Env("VOYAGEAI_API_KEY") },
voice = new { driver = "elevenlabs", key = Env("ELEVENLABS_API_KEY") },
azure = new
{
driver = "azure",
resource = "contoso", // https://contoso.openai.azure.com/openai/v1/
key = Env("AZURE_OPENAI_API_KEY"),
models = new { text = "my-gpt-deployment", embeddings = "my-embedding-deployment" },
},
groq = new { driver = "groq", key = Env("GROQ_API_KEY") },
anthropic = new
{
driver = "anthropic",
key = Env("ANTHROPIC_API_KEY"),
models = new
{
text = "claude-sonnet-4-5",
cheapest = "claude-haiku-5-5",
smartest = "claude-opus-5-5",
},
// Optional prices per million tokens, used for cost estimates.
pricing = new Dictionary<string, object>
{
["claude-sonnet-4-5"] = new { input = 3.00, output = 15.00, cached_input = 0.30 },
},
},
gemini = new
{
driver = "gemini",
key = Env("GEMINI_API_KEY"),
models = new
{
text = "gemini-3.5-flash",
images = "gemini-2.5-flash-image",
audio = "gemini-3.8-flash-tts",
transcription = "gemini-3.5-flash",
embeddings = "gemini-embedding-2",
},
},
local = new
{
driver = "openai-compatible",
url = "http://localhost:11434/v1",
models = new { text = "llama3.2", embeddings = "nomic-embed-text" },
},
},
};
}The model values above are the built-in defaults. Cohere defaults to rerank-v3.5 and embed-v4.0. OpenAI-compatible endpoints require a URL and a model for each generation feature used; the key is optional. Models and feature availability depend on the endpoint. url includes the API version path, such as /v1; it may also override a native provider's base URL.
Environment variables such as ai__default=local and ai__providers__local__models__text=llama3.2 override configuration. When no key is configured, each driver reads {DRIVER}_API_KEY directly: OPENAI_API_KEY, ANTHROPIC_API_KEY, GEMINI_API_KEY, COHERE_API_KEY, XAI_API_KEY, GROQ_API_KEY, MISTRAL_API_KEY, DEEPSEEK_API_KEY, OPENROUTER_API_KEY, JINA_API_KEY, VOYAGEAI_API_KEY, ELEVENLABS_API_KEY, and AZURE_API_KEY (or AZURE_OPENAI_API_KEY).
models.cheapest and models.smartest are used by [UseCheapestModel] / [UseSmartestModel] agents and AiOptions.Tier. Built-in tiers exist for OpenAI (gpt-5-nano / gpt-5), Anthropic (claude-haiku-5-5 / claude-opus-5-5), Gemini (gemini-3.5-flash-lite / gemini-3.1-pro-preview), xAI, Groq, Mistral, and DeepSeek; configure them for other drivers.
Laravel-style API
| Laravel | DotBlaze |
|---|---|
SalesCoach::make()->prompt('...') | await SalesCoach.Make().Prompt("...") |
(new SalesCoach)->prompt('...') | await new SalesCoach().Prompt("...") |
agent()->prompt('...') | await Ai.Agent().Prompt("...") |
Image::of('...')->landscape()->generate() | await Image.Of("...").Landscape().Generate() |
Audio::of('...')->voice('coral')->generate() | await Audio.Of("...").Voice("coral").Generate() |
Transcription::fromStorage('audio.mp3')->generate() | await Transcription.FromStorage("audio.mp3").Generate() |
Embeddings::for($texts)->dimensions(1536)->generate() | await Embeddings.For(texts).Dimensions(1536).Generate() |
Reranking::of($documents)->limit(5)->rerank('query') | await Reranking.Of(documents).Limit(5).Rerank("query") |
Document::fromPath('notes.txt')->put() | await Files.Document.FromPath("notes.txt").Put() |
Stores::create('Knowledge') | await Stores.Create("Knowledge") |
SalesCoach::fake(['Answer']) | SalesCoach.Fake("Answer") |
#[Provider('anthropic')], #[UseCheapestModel], #[MaxSteps(5)] | [Provider("anthropic")], [UseCheapestModel], [MaxSteps(5)] |
$agent->stream('...')->then(fn ($response) => ...) | agent.Stream("...").Then(response => ...) |
$agent->queue('...')->then(...)->catch(...) | agent.Queue("...").Then<Handler>().Catch<FailureHandler>() |
Event::listen(AgentPrompted::class, ...) | Event.Listen<AgentPrompted>(...) |
The fluent classes use the same validation, provider selection, failover, and usage tracking as Ai.Generate(new GenerateImages(...)) and the injectable IAi service. Those lower-level request APIs are also available.
Providers
| Connection | Supported operations |
|---|---|
| OpenAI | Responses API agents/tools/structured output/streaming/classification; hosted web/file search and code execution; images/edits, speech, transcription/diarization, embeddings, files, vector stores |
| OpenAI-compatible | Chat Completions agents/tools/structured output/streaming/classification, plus generation/storage endpoints implemented by your provider |
| Anthropic (native Messages API) | Chat, function/MCP tools, hosted web search/code execution, structured output, streaming, chat-based classification, image/PDF inputs |
| Gemini (native generateContent API) | Chat, function/MCP tools, hosted web/file search/code execution, structured output, streaming, classification; image generation/editing, PCM/WAV speech, transcription, text/multimodal embeddings; file uploads and file search stores |
Azure OpenAI (azure) | Chat Completions agents/tools/structured output/streaming, plus images, speech, transcription, embeddings, files, and vector stores on the v1 API |
| xAI, Groq, Mistral, DeepSeek, OpenRouter, Ollama | Chat Completions presets with built-in URLs, keys, and default models; plus the generation endpoints each service offers (xAI images, Groq transcription, Mistral transcription/diarization and embeddings, Ollama embeddings) |
| Cohere | Reranking, embeddings |
Jina, Voyage AI (jina, voyageai) | Embeddings, reranking |
ElevenLabs (elevenlabs) | Speech (mp3/pcm/opus by voice ID), transcription with speaker diarization |
Keyed IAiGateway | Custom configurable chat drivers, reusable across named providers |
Keyed IChatClient | Chat, tools, structured output, classification, streaming, subject to the adapter's capabilities |
Keyed IAiGenerator | Custom generation/retrieval implementations |
The preset drivers reuse the OpenAI-compatible gateway with each service's base URL (https://api.x.ai/v1/, https://api.groq.com/openai/v1/, https://api.mistral.ai/v1/, https://api.deepseek.com/v1/, https://openrouter.ai/api/v1/, http://localhost:11434/v1/); url overrides it. OpenRouter, Ollama, and Azure have no default model: configure models.text (for Azure, the deployment name). Azure uses the v1 endpoint built from resource, or an explicit url ending in /openai/v1/, and sends the key in the api-key header. Other OpenAI-compatible URLs still work with driver = "openai-compatible". You may also register an existing Microsoft.Extensions.AI.IChatClient adapter for a particular provider:
services.AddKeyedSingleton<IChatClient>("custom", (sp, key) => CreateYourChatClient());Here, CreateYourChatClient() is your application's adapter factory. Use the registered name with new AiOptions("custom"). DI owns registered clients; the AI SDK does not dispose them after requests. Custom media providers implement IAiGenerator and are registered the same way.
Native HTTP Gateways
Use the configured provider name directly:
var openai = await Ai.Agent("Answer concisely.")
.Prompt("Explain dependency injection.", provider: "openai");
var claude = await Ai.Agent("Answer concisely.")
.Prompt("Explain dependency injection.", provider: "anthropic");
var gemini = await Ai.Agent("Answer concisely.")
.Prompt("Explain dependency injection.", provider: "gemini");These gateways use HttpClient against the native APIs. The named DotBlaze.AI client's timeout covers both headers and the complete response body for chat, media, retrieval, and storage:
| Driver | Gateway / chat endpoint | Default base URL | Authentication |
|---|---|---|---|
openai | OpenAiGateway → responses | https://api.openai.com/v1/ | Authorization: Bearer ... |
openai-compatible | OpenAiCompatibleGateway → chat/completions | Configured url, including its API version path | Bearer token when a key is present |
anthropic | AnthropicGateway → messages | https://api.anthropic.com/v1/ | x-api-key, with anthropic-version: 2023-06-01 |
gemini | GeminiGateway → generateContent / streamGenerateContent | https://generativelanguage.googleapis.com/v1beta/ | x-goog-api-key |
azure | OpenAiCompatibleGateway → chat/completions | https://{resource}.openai.azure.com/openai/v1/ | api-key: ... |
xai, groq, mistral, deepseek, openrouter, ollama | OpenAiCompatibleGateway → chat/completions | The service's API (see above) | Authorization: Bearer ... (optional for Ollama) |
They translate one model step at a time. The existing agent pipeline executes tools, feeds results into subsequent steps, and stores completed conversation turns. All gateways use the same Prompt / Stream API.
The OpenAI gateway sends Responses API input items, flat function definitions, function_call / function_call_output items, and max_output_tokens. It uses store: false and resends local history, requesting reasoning.encrypted_content so reasoning IDs and encrypted state survive tool steps and database continuation. Existing stored Chat Completions messages and tool results are also mapped into Responses input; no conversation migration is needed. Gemini tool-call thought signatures likewise survive continuation.
The compatible gateway independently uses Chat Completions messages, nested function definitions, tool_calls, and max_tokens. An endpoint implementing only Chat Completions should use driver = "openai-compatible" with its URL, key, and model configured.
Structured<T>() sends OpenAI Responses text.format, Chat Completions response_format.json_schema, Anthropic output_config.format, or Gemini generationConfig.responseJsonSchema. Use a model that supports native structured output. Anthropic requires an explicit schema; plain ChatResponseFormat.Json without a schema is unsupported. Some Anthropic schema constraints are expressed as descriptions because its schema subset does not accept them; the agent still performs its documented deserialization and recursive data-annotation checks.
Common chat options include model, instructions, temperature, output-token limits, top-p, function tools, and tool choice. Anthropic/Gemini and OpenAI-compatible endpoints also map top-k and stop sequences. Gemini and OpenAI-compatible map seed and frequency/presence penalties. The Responses gateway rejects those Chat Completions-only options rather than silently discarding them.
Prompt caching. [CachePrompt] on an agent, or ChatOptions.AdditionalProperties[AiChatOptions.CachePrompt] = true, sends Anthropic's top-level cache_control: {type: "ephemeral"} so the stable prefix (tools, system prompt, earlier turns) is cached; set AiChatOptions.CacheTtl to "1h" for the longer lifetime. Cache reads appear as UsageDetails.CachedInputTokenCount. OpenAI and Gemini cache long prefixes automatically and ignore the flag. Keep instructions and tools stable between requests, since any change to the prefix invalidates the cache.
OpenAI Responses maps Reasoning.Effort and requests concise/detailed provider summaries for Reasoning.Output.Summary / Full. The compatible gateway maps Reasoning.Effort only. Anthropic maps reasoning to native thinking controls: legacy models use token budgets (Low 1024, Medium/default 8192, High 16384, ExtraHigh 32768); adaptive models use output_config.effort. Legacy MaxOutputTokens must exceed the thinking budget; if omitted, the SDK adds 4096 output tokens. Thinking rejects forced tool choice and incompatible sampling options. Output.None omits displayed thinking, while Summary/Full request provider summaries, not raw chain-of-thought. Gemini maps effort to thinkingBudget for 2.5 models and thinkingLevel for 3-series models, and output to includeThoughts. Gemini 2.5 Pro and Gemini 3 reject disabling thinking; unsupported Gemini model families reject explicit effort rather than silently ignoring it. Choose a provider/model supporting these controls. Responses streams map response.* SSE events; tool calls are released only after a valid terminal response. A token-limited text response reports ChatFinishReason.Length, while incomplete tool-call steps fail without executing their tools.
OpenAI Remote History and Background Responses
Remote history is available through the low-level Ai.Chat() client, separately from Agent.Continue() and database history:
using var client = Ai.Chat(new AiOptions("openai"));
var first = await client.GetResponseAsync([new(ChatRole.User, "Remember this context.")], new()
{
AdditionalProperties = new() { [OpenAiGateway.StoreResponses] = true },
});
var next = await client.GetResponseAsync([new(ChatRole.User, "Follow-up question.")], new()
{
ConversationId = first.ConversationId,
});A resp_... ID maps to previous_response_id; an existing conv_... ID maps to OpenAI's conversation. Send only new messages and resend instructions you need on each call. Explicit storage, remote history, or background generation opts into provider-side retention; the default remains store: false. Do not expose another user's conversation IDs to callers.
For long-running non-streamed responses:
var pending = await client.GetResponseAsync([new(ChatRole.User, "Analyze this material.")],
new() { AllowBackgroundResponses = true }, cancellationToken);
// On a later poll, use the same provider configuration and no new messages/options.
if (pending.ContinuationToken is { } token)
pending = await client.GetResponseAsync([], new() { ContinuationToken = token }, cancellationToken);Poll at an application-controlled interval until ContinuationToken is null. Pending responses contain no messages or executable tool calls. Tokens can be persisted using ToBytes() and restored with ResponseContinuationToken.FromBytes(...); they are authenticated and bound to the provider name, endpoint, credentials, and configured headers. Changing those settings invalidates the token. Keep tokens private and enforce application ownership when retrieving them.
Remote operations never automatically fail over to another provider/account. Cancelling the HTTP request does not cancel an already-created provider job. Background streaming/resumption is supported as described below. RawRepresentationFactory remains explicitly unsupported. Other gateways reject remote history/background options. High-level Agent and queued invocations reject remote state: use local Continue() there, or use Ai.Chat() and manage provider responses yourself. Non-streamed ChatResponse.RawRepresentation contains provider JSON as a JsonElement; HTTP failures surface as HttpRequestException.
Resuming a Background Stream
Start with AllowBackgroundResponses = true and retain each update together with its checkpoint:
ResponseContinuationToken? checkpoint = null;
await foreach (var update in client.GetStreamingResponseAsync(
[new(ChatRole.User, "Produce a detailed analysis.")],
new() { AllowBackgroundResponses = true }, cancellationToken))
{
// Persist/process the update and checkpoint together before requesting the next one.
checkpoint = update.ContinuationToken;
// A FinishReason marks terminal completion: clear the saved checkpoint.
}
// In recovery after a transport failure, restore the last persisted checkpoint.
if (checkpoint is not null)
{
await foreach (var update in client.GetStreamingResponseAsync([],
new() { ContinuationToken = checkpoint }, cancellationToken))
{
checkpoint = update.ContinuationToken;
// Append/process only these new updates.
}
}The SDK resumes with GET responses/{id}?stream=true&starting_after={sequence}. It never resubmits the original prompt. Checkpoints contain the last event position and delivered-item/text/reasoning state, authenticated against the same provider configuration as polling tokens. Poll and stream tokens are not interchangeable. Background streams must be created as streams; a background response started with non-streaming polling cannot later be resumed as a stream.
Metadata-only updates may carry checkpoints without text. Keepalives are not checkpoints. Tool calls remain withheld until a valid terminal response; when a disconnect occurs midway through delivering its items, the terminal event is replayed while delivered items are skipped. An interrupted stream throws rather than reporting success; retain the latest checkpoint outside the failed enumeration. A terminal update has FinishReason and no continuation token.
This is provider transport recovery, not exactly-once application side effects. Store output and checkpoint atomically and make tool execution idempotent using call IDs. Reusing an older checkpoint intentionally replays output after that checkpoint. Checkpoints include identifiers/state, not response text, and are bounded to 64 KiB of payload; exceeding this fails explicitly. Recovery requires the provider to retain the background response. Cancellation stops the connection, not the remote job. Reconnecting browsers still need your application's event persistence/replay. Gemini generation uses generateContent and batchEmbedContents. Gemini files and file search stores are managed through Files and Stores (see Files and Vector Stores). Models must support the selected endpoint and feature. The configured model names can be changed independently for every feature.
Custom Gateways
Implement IAiGateway to register a reusable chat driver, similar to Laravel's gateway boundary:
public interface IAiGateway
{
IChatClient CreateChatClient(
string provider,
IConfigurationSection configuration,
string? model = null);
}provider is the configured name, and configuration is its ai:providers:{name} section. model contains an explicit AiOptions.Model override when provided; the client should otherwise use its configuration/default and honor per-request ChatOptions.ModelId. Return a new, caller-owned IChatClient: the manager disposes it after the model step or stream ends.
For example, an application gateway can reuse the native Anthropic HTTP implementation for a company proxy. Create app/Ai/Gateways/CompanyGateway.cs:
using DotBlaze.ArtificialIntelligence;
using Microsoft.Extensions.AI;
using Microsoft.Extensions.Configuration;
namespace App.Ai.Gateways;
public sealed class CompanyGateway(IHttpClientFactory http) : IAiGateway
{
public IChatClient CreateChatClient(
string provider, IConfigurationSection configuration, string? model = null)
{
return new AnthropicGateway(http)
.CreateChatClient(provider, configuration, model);
}
}Register the driver name in an application provider's Register method:
services.AddKeyedSingleton<IAiGateway, App.Ai.Gateways.CompanyGateway>("company");Then add a named provider to AiConfig.Values():
company = new
{
driver = "company",
url = "https://ai.example.com/anthropic/v1/",
key = Env("COMPANY_AI_KEY"),
models = new { text = "claude-sonnet-4-5" },
headers = new Dictionary<string, string> { ["X-Tenant"] = "sales" },
},Call it with provider: "company". Multiple provider entries may select the same driver with different URLs, credentials, headers, or models. All built-in chat and generation/storage requests read the optional headers section for custom request headers. A Responses API proxy can reuse OpenAiGateway; a Chat Completions proxy should reuse OpenAiCompatibleGateway.
For a different wire protocol, return your own IChatClient implementation from the gateway. The implementations in src/DotBlaze.AI/Gateways/OpenAiGateway.cs, OpenAiCompatibleGateway.cs, AnthropicGateway.cs, and GeminiGateway.cs show message/tool mapping, JSON Schema output, SSE parsing, and usage translation. A gateway performs one provider step; it should not run tools or implement its own agent loop. Respect cancellation, preserve tool-call IDs and provider metadata needed on subsequent steps, and propagate failures instead of returning an empty successful response. Normalize transport failures to HttpRequestException with the HTTP status code so the manager can apply its transient-error failover rules.
Resolution order is a keyed IChatClient for the provider name, a keyed IAiGateway for the driver name, then the built-in driver. Registering an IAiGateway under a built-in driver name replaces that driver's chat implementation. Existing failover and usage recording apply to gateway-created clients too.
Agents
var response = await Ai.Agent("You are a concise sales coach.")
.Prompt("How should I follow up after a demo?");
var text = response.Text;
var usage = response.Usage;Define a named agent using the same self-typed pattern as DotBlaze models:
Generate the class with dotblaze make:agent SalesCoach. Tools can be generated with dotblaze make:tool SumTool. These write to app/Ai/Agents and app/Ai/Tools. All three AI generators (make:agent, make:agent-middleware, make:tool) are owned by DotBlaze.AI: install the package first or the commands will not appear in dotblaze list and cannot run. They run through the application, so it must build successfully; dotnet run -- make:agent SalesCoach also works. Nested names and --force/-f are supported.
public sealed class SalesCoach : Agent<SalesCoach>
{
public override string Instructions { get; init; } =
"Analyze sales conversations and suggest the next action.";
}
var response = await SalesCoach.Make().Prompt(
"Review this transcript...", provider: "openai", model: "gpt-4.1-mini");SalesCoach.Make() and Ai.Agent<SalesCoach>() create a new instance through DI. You may pass constructor arguments to Make(...); remaining dependencies come from the container. Agents without constructor dependencies can also be instantiated with new SalesCoach(). Services are resolved from the current scope when used. Explicit IAi and IConversationStore constructor injection is still supported.
Generate a typed structured-output agent with dotblaze make:agent ReviewAgent --structured, and agent middleware with dotblaze make:agent-middleware LogPrompts (written to app/Ai/Middleware).
Use named provider and model arguments on Prompt, Stream, and Structured<T>. Pass AiOptions for failover and ChatOptions for temperature, output limits, or other .NET chat settings. Named provider/model arguments override AiOptions, and its model overrides ChatOptions.ModelId. Async methods accept a cancellation token.
Agent Configuration
Attributes set an agent's defaults, like Laravel's agent attributes:
[Provider("anthropic", "openai")] // default provider, then failover providers in order
[Model("claude-sonnet-4-5")]
[Temperature(0.3)]
[MaxTokens(2048)]
[MaxSteps(5)] // model/tool round trips per prompt (default 10)
[Timeout(60)] // seconds, covering the whole prompt including tools
public sealed class SalesCoach : Agent<SalesCoach> { ... }
[UseCheapestModel] // or [UseSmartestModel]
[CachePrompt]
public sealed class Summarizer : Agent<Summarizer> { ... }Each attribute backs a virtual property (Providers, Model, Temperature, MaxTokens, MaxToolSteps, Timeout, ModelTier, CachePrompt) that you may override instead, for example to read configuration. Call arguments always win: provider:/model: or AiOptions replace the agent's provider and model, and explicit ChatOptions.Temperature/MaxOutputTokens replace the attribute values. [Model] applies to the first provider; failover providers use their own configured model. A tier applies only when neither the call nor the agent names a model. Queued agents are recreated on the worker, so their attributes apply there too.
Conversations
var first = await SalesCoach.Make()
.ForUser("12")
.Prompt("My customer needs a lower price.");
var next = await SalesCoach.Make()
.Continue(first.ConversationId!, "12")
.Prompt("What should I offer?");Choose the user ID from the authenticated application context. The database store accepts non-negative numeric IDs (up to long.MaxValue), passed as strings to ForUser / Continue, and stores them in nullable BIGINT user_id columns. Keys such as "user:12" or "tenant:4:user:12" are not supported by this store. Stored conversations are scoped to both user and agent class. Continuing with a different user or class fails before contacting the provider. Multi-tenant applications must use globally unique user IDs or a custom IConversationStore with tenant scoping.
ContinueOrStart(conversationId, asUser) starts a conversation when the ID is null, and continues it otherwise. ForParticipant(key) is an alias for ForUser(key).
agent_conversations stores id, user_id, title, version, and timestamps. The title is the first user message truncated to 255 characters. agent_conversation_messages stores one row per chat message with id, conversation_id, user_id, agent, role, content, attachments, steps, usage, meta, status, and timestamps. Neither table uses participant_type or participant_id. JSON steps retain the complete .NET chat message, including tool calls, results, and provider metadata; meta.sequence preserves message order even when timestamps match. attachments contains media/file content and usage contains any message-level usage details.
Customize the names through ai.conversations.tables.conversations and ai.conversations.tables.messages in config/Ai.cs (shown above). Both the store and migration, including rollback, use these settings. Set them before running dotblaze migrate; changing config alone does not rename existing tables.
Concurrent updates retain a version check: a stale completion throws rather than overwriting another turn. The conversation update and all message inserts run in one transaction. A stream is stored only after full enumeration. Failed or abandoned turns are not stored; tools may already have executed, so do not blindly retry side-effecting tools.
Existing installations: if the original ai_conversations migration has already run, it will not run again. Add an application migration that calls new CreateAiConversationsTable().Up() to create the new tables, then explicitly map old owner keys to numeric user IDs and import their history before switching traffic. Keep the old table and application version available for rollback; existing data is not converted automatically. Do not change table-name config while old and new application versions are sharing the same deployment.
Without ForUser or Continue, prompts are independent. Supply explicit history with WithMessages(IEnumerable<ChatMessage>), including .NET image/document content where the provider supports it. Explicit history and stored conversations cannot be combined. Use a separate agent instance for each conversation.
Context limits and conversation management
Limit the number of prior user turns sent to the model:
var response = await SalesCoach.Make()
.Continue(conversationId, userId)
.WithContextLimit(20)
.Prompt("Continue.");Alternatively, override public override int? MaxConversationTurns => 20; on the agent. The default is null for compatibility. A turn includes all its tool calls, results, and assistant messages; trimming never separates a result from its call. System/developer instructions are retained. The database store loads only the retained turns, while the full history stays in the database and message sequences continue from the original count. This is a turn limit, not a token counter: one very large turn still needs application-level size limits.
An optional estimated input budget can trim older complete turns, or summarize discarded history:
var response = await SalesCoach.Make()
.Continue(conversationId, userId)
.WithContextTokenBudget(8000, summarize: true, maxSummaryTokens: 256)
.Prompt("Continue.");The budget preserves system/developer instructions and the current prompt. If those cannot fit, the call fails before generation. Trimming and summaries only change model input, never rewrite database history. Summarization uses at most one additional bounded model call, with no tools and the same cancellation deadline; it costs an additional request. Oversized discarded turns may be omitted, and a summary that does not fit is discarded.
AgentContextBudget.Estimate uses UTF-8 JSON size (four bytes per token plus message overhead), not a model tokenizer. The budget is an approximation of input size, not a guaranteed context-window limit or an output allowance. Keep headroom for model-specific tokenization and tool output, especially with attachments. WithContextLimit is applied first; history already excluded by that limit cannot be summarized.
The injected store provides owner- and agent-scoped listing, message pagination, and transactional deletion:
var store = ServiceScope.Current.GetRequiredService<IConversationStore>();
var agentType = typeof(SalesCoach).FullName!;
var conversations = await store.Paginate(userId, agentType, perPage: 20, page: 1);
var messages = await store.PaginateMessages(conversationId, userId, agentType, perPage: 25);
await store.Delete(conversationId, userId, agentType);These return DotBlaze Paginator<T> values. Conversations are newest-updated first; messages are newest-sequence first, including when timestamps match. Page sizes are 1–100. Deletion removes the conversation and its messages together and rejects a concurrent update. A different owner or agent cannot read or delete the conversation. Custom stores may implement the new management methods; their defaults throw NotSupportedException. LoadRecent defaults to loading and trimming for existing custom stores; override it for efficient bounded reads.
Attachments
Prompt, Structured<T>, Stream, Queue, and BroadcastOnQueue accept an attachments argument. It belongs to the current user message and works with ForUser and Continue:
var pdf = await Files.Document.FromStorage("manual.pdf").ToContent("application/pdf");
var image = new DataContent(await File.ReadAllBytesAsync("photo.png"), "image/png");
var response = await SalesCoach.Make().ForUser(userId)
.Prompt("Summarize this document and image.", attachments: [pdf, image]);
await SalesCoach.Make().Continue(response.ConversationId!, userId)
.Queue("Check this version.", attachments: [pdf]).OnQueue("ai");Use DataContent for bytes, UriContent for a provider-readable URL, or Files.Document.FromId(id).ToContent(mediaType) for a hosted file. Support varies by provider; hosted OpenAI file IDs are not Gemini file URIs. File sources are read by ToContent before dispatch, and inline bytes are serialized into the queue payload. Validate upload sizes in the application. Attachments are stored with completed turns; abandoned streams are not saved.
Agent Middleware
Override Middleware() to wrap the complete agent tool loop using standard .NET DelegatingChatClient implementations:
public override IEnumerable<Func<IChatClient, IChatClient>> Middleware() =>
[
inner => new RequestLoggingClient(inner, logger),
];RequestLoggingClient is an application class derived from DelegatingChatClient. Override GetResponseAsync and GetStreamingResponseAsync for the paths you need. Wrappers run outermost-first in declaration order, once around the whole tool loop, and must forward cancellation. Their disposal owns the inner client. Queued named agents recreate their middleware through the agent's DI constructor and Middleware() method. Structured-output validation and conversation persistence still happen after the pipeline completes successfully.
Structured Output and Classification
public sealed record Review(string Feedback, int Score);
var result = await SalesCoach.Make().Structured<Review>("Review this call...");
Console.WriteLine(result.Value.Feedback);
var label = await Classification.Of("The delivery was excellent.")
.Labels("positive", "neutral", "negative")
.Classify(provider: "openai");Structured output sends a JSON Schema derived from the C# type, deserializes with required constructor parameters and nullable annotations enforced, and checks data annotations such as [Range] recursively on nested objects, collection elements, and dictionary values. Reference cycles are visited only once. Invalid output is not added to conversation history; the same validation applies to queued structured output.
Classification uses a chat model with a constrained label schema and rejects labels outside the supplied set.
Ask a question about the text and receive the answer with probabilities:
var spam = await Classification.Of(message).Boolean("Is this spam?");
if (spam.Value && spam.Confidence > 0.8) { ... }
var team = await Classification.Of(ticket).Choice("Which team should handle this?", ["billing", "bugs", "sales"]);
var sentiment = await Classification.Of(review).Score("How positive is this review?", min: 1, max: 5);
Console.WriteLine($"{team.Value}: {team.Probabilities["billing"]:P0}");Each ClassificationResult<T> has Value, Confidence (the probability of the chosen answer), and Probabilities for every option, normalized to sum to 1. It converts implicitly to T. The probabilities are the model's own estimates returned through structured output, not token log-probabilities, so treat them as a ranking signal rather than calibrated values. Scores are integers in a range of at most 101 values. Fake them with Classification.Fake() and Respond("{\"choice\":\"yes\",\"probabilities\":[...]}").
Tools and MCP
Tools give the model access to your application's code. A tool is an ordinary C# method wrapped with AIFunctionFactory.Create. The wrapper exposes its name, description, and argument schema to the model; the agent invokes the method when the model requests it.
Provider-hosted Tools
The installed Microsoft.Extensions.AI types also enable tools executed by the provider:
public override IEnumerable<AITool> Tools() =>
[
new HostedWebSearchTool(),
new HostedFileSearchTool
{
Inputs = [new HostedVectorStoreContent("vs_123")],
MaximumResultCount = 5,
},
new HostedCodeInterpreterTool
{
Inputs = [new HostedFileContent("file_123")],
},
];This complete combination targets OpenAI. Anthropic supports web search and code execution without Inputs; it does not offer this file-search tool. Gemini supports all three, with fileSearchStores/... names, no MaximumResultCount, and no code-execution Inputs. OpenAI-compatible Chat Completions rejects hosted tools. Function/MCP tools can still be included on the same agent when the provider/model supports the combination.
Tool constructors accept provider-specific AdditionalProperties, such as OpenAI file-search filters (new VectorSearchFilter("tenant", "a").ToProviderFilter()) or Gemini metadataFilter. The tool type/name cannot be overridden. Hosted results are represented by ToolCallContent / ToolResultContent, never executed as local functions, and their provider payloads survive stored continuation. Inspect AdditionalProperties["dotblaze.provider.openai"] (or anthropic / gemini) for those payloads, and AdditionalProperties["dotblaze.citations"] on response content for citations/grounding.
For provider-managed URL retrieval, use DotBlaze's HostedWebFetchTool on Anthropic or Gemini:
// Anthropic: limit retrieval to your public documentation domain.
new HostedWebFetchTool(new Dictionary<string, object?>
{
["allowed_domains"] = new[] { "docs.example.com" },
["max_uses"] = 3,
["max_content_tokens"] = 10000,
});
// Gemini URL context accepts no tool options.
new HostedWebFetchTool();The provider fetches the URL; DotBlaze does not perform an application-side HTTP fetch. Anthropic supports provider options such as domain restrictions and citations. Gemini URL context does not accept those restrictions and rejects nonempty tool options rather than ignoring them. OpenAI and Chat Completions reject this tool. Treat fetched content as untrusted data and avoid exposing sensitive information through URLs generated from model input.
Anthropic code containers are retained in conversation metadata. When a long-running server tool returns pause_turn, the gateway resends the paused turn and continues automatically, for both Prompt and Stream, up to AnthropicGateway.MaxPauseContinuations (5) times; the combined turn is stored as one answer, and only the final finish reason is reported.
The examples below use this application layout. Replace App with your application's root namespace:
app/
Ai/
Agents/
MathAgent.cs
WeatherAgent.cs
Tools/
SumTool.cs
GetWeatherTool.cs
Providers/
WeatherToolsProvider.csMathAgent and SumTool form a complete, dependency-free tool example. The weather files demonstrate an asynchronous tool with an injected HTTP client.
Defining a Tool Class
Create app/Ai/Tools/SumTool.cs:
using System.ComponentModel;
namespace App.Ai.Tools;
public sealed class SumTool
{
[Description("Add two integers and return their sum.")]
public int Handle(
[Description("The first integer.")] int a,
[Description("The second integer.")] int b)
{
return checked(a + b);
}
}Handle is a naming convention: you can wrap any suitable method. The method's [Description] describes the tool, and parameter descriptions help the model supply useful arguments. The factory derives the input JSON Schema from the parameter names and C# types. Here, a and b are required integers.
Return the tool's result directly: a string, number, serializable object, or collection. The pipeline serializes it for the model. Use Task<T> or ValueTask<T> for asynchronous work.
Registering Tools on an Agent
Create app/Ai/Agents/MathAgent.cs:
using App.Ai.Tools;
using DotBlaze.ArtificialIntelligence;
using Microsoft.Extensions.AI;
namespace App.Ai.Agents;
public sealed class MathAgent : Agent<MathAgent>
{
public override string Instructions { get; init; } =
"Use the sum tool for addition. Report the tool's result.";
public override IEnumerable<AITool> Tools() =>
[
AIFunctionFactory.Create(new SumTool().Handle, name: "sum"),
];
}Tools() declares the tools this agent exposes. Add more AIFunctionFactory.Create(...) entries to expose more methods, using a distinct, stable name for each. Creating a .cs file alone does not expose its methods to the model.
The SumTool instance above has no dependencies, so the agent constructs it directly. For tools with dependencies, use the DI pattern below.
Calling an Agent with Tools
Call the agent inside a DotBlaze request, controller, command, or job:
using App.Ai.Agents;
var response = await MathAgent.Make().Prompt(
"Use sum to calculate 12 + 30.",
provider: "openai",
model: "gpt-4.1-mini");
Console.WriteLine(response.Text);MathAgent.Make() constructs the agent through the container. This agent can also be instantiated with new MathAgent(), since it has no constructor dependencies. In standalone/background code, establish a scope using ServiceScope.Run(services, ...).
A tool-enabled prompt proceeds as follows:
- The agent sends its instructions, messages, and tool definitions to the provider.
- The model may request
sumwith arguments such as{"a":12,"b":30}. - The pipeline binds those arguments and invokes
SumTool.Handle(12, 30). - It sends the result,
42, back to the model. - The model returns a final answer or requests another tool.
The model decides whether a tool is needed; merely providing a tool does not guarantee a call. The provider/model must support tool calling.
Stream(...) uses the same tool pipeline:
await foreach (var update in MathAgent.Make().Stream(
"Use sum to calculate 12 + 30.",
cancellationToken: cancellationToken))
{
Console.Write(update.Text);
}cancellationToken is the caller's token, such as HttpContext.RequestAborted. Inspect update.Contents for tool-related content rather than expecting every update to contain text.
Asynchronous Tools and Dependency Injection
For an HTTP-backed tool, inject IHttpClientFactory and accept a CancellationToken in the handler.
Create app/Ai/Tools/GetWeatherTool.cs:
using System.ComponentModel;
using System.Text.Json;
namespace App.Ai.Tools;
public sealed record WeatherReading(
double Latitude, double Longitude, double TemperatureCelsius);
public sealed class GetWeatherTool(IHttpClientFactory clients)
{
[Description("Get the current temperature in Celsius for geographic coordinates.")]
public async Task<WeatherReading> Handle(
[Description("Latitude between -90 and 90.")] double latitude,
[Description("Longitude between -180 and 180.")] double longitude,
CancellationToken cancellationToken = default)
{
if (!double.IsFinite(latitude) || latitude is < -90 or > 90)
throw new ArgumentOutOfRangeException(nameof(latitude));
if (!double.IsFinite(longitude) || longitude is < -180 or > 180)
throw new ArgumentOutOfRangeException(nameof(longitude));
using var client = clients.CreateClient("weather");
var url = FormattableString.Invariant(
$"forecast?latitude={latitude}&longitude={longitude}¤t=temperature_2m&temperature_unit=celsius");
using var response = await client.GetAsync(url, cancellationToken);
response.EnsureSuccessStatusCode();
await using var stream = await response.Content.ReadAsStreamAsync(cancellationToken);
using var json = await JsonDocument.ParseAsync(
stream, cancellationToken: cancellationToken);
var temperature = json.RootElement
.GetProperty("current")
.GetProperty("temperature_2m")
.GetDouble();
return new WeatherReading(latitude, longitude, temperature);
}
}Register the tool and its named HTTP client in app/Providers/WeatherToolsProvider.cs:
using App.Ai.Tools;
using DotBlaze;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
namespace App.Providers;
public sealed class WeatherToolsProvider : Provider
{
public override void Register(IServiceCollection services, IConfiguration config)
{
services.AddHttpClient("weather", client =>
{
client.BaseAddress = new Uri("https://api.open-meteo.com/v1/");
client.Timeout = TimeSpan.FromSeconds(10);
});
services.AddScoped<GetWeatherTool>();
}
}DotBlaze discovers application service providers automatically. The weather example calls Open-Meteo over HTTP; its timeout and HTTP failures are handled by the tool pipeline.
Create app/Ai/Agents/WeatherAgent.cs:
using App.Ai.Tools;
using DotBlaze.ArtificialIntelligence;
using Microsoft.Extensions.AI;
namespace App.Ai.Agents;
public sealed class WeatherAgent(GetWeatherTool weather) : Agent<WeatherAgent>
{
public override string Instructions { get; init; } =
"Use get_weather for temperatures. Ask for coordinates if they are unknown.";
public override IEnumerable<AITool> Tools() =>
[
AIFunctionFactory.Create(weather.Handle, name: "get_weather"),
];
}Then use Make() so the container supplies GetWeatherTool:
using App.Ai.Agents;
var response = await WeatherAgent.Make().Prompt(
"What is the temperature at latitude -6.2, longitude 106.8?",
cancellationToken: cancellationToken);The .NET pipeline supplies the handler's CancellationToken; it is not a model-supplied argument and is excluded from the input schema. Pass it to the tool's asynchronous operations.
The same constructor-injection pattern works for database or application services. Keep credentials and authenticated-user/tenant context in those services rather than accepting them as model-supplied arguments.
Arguments, Validation, and Errors
- Schema: method parameter names, types, and descriptions define the model-facing arguments. Inspect the generated schema with
AIFunctionFactory.Create(tool.Handle, name: "...").JsonSchema. - Validation: validate domain constraints inside the handler. A description such as “latitude between -90 and 90” explains the rule but does not enforce it.
GetWeatherToolchecks that range before making a request;SumToolusescheckedto reject integer overflow. - Results: return the data the model needs. A record such as
WeatherReadingis serialized as structured tool-result data. - Errors: handler failures use the .NET pipeline's non-detailed tool-error responses, allowing the model to react. Provider failures and caller cancellation can still terminate the operation.
- Execution: tools run sequentially. The default limit is ten model iterations, including tool follow-up requests. Override
MaxToolStepson the agent to set another limit.
For example, add this property to an agent to limit its model iterations:
public override int MaxToolSteps => 5;Runtime Tool Overrides
Use WithTools(...) to replace the tools declared by one agent instance:
using App.Ai.Agents;
using App.Ai.Tools;
using Microsoft.Extensions.AI;
var response = await MathAgent.Make()
.WithTools([AIFunctionFactory.Create(new SumTool().Handle, name: "sum")])
.Prompt("Use sum to calculate 12 + 30.");For an anonymous agent, supply the tools the same way:
var response = await Ai.Agent("Use sum for addition.")
.WithTools([AIFunctionFactory.Create(new SumTool().Handle, name: "sum")])
.Prompt("Use sum to calculate 12 + 30.");WithTools replaces the declared list rather than appending to it. To retain declared tools, include them explicitly, for example .WithTools([.. agent.Tools(), extraTool]). WithInstructions(...) overrides instructions for that instance.
Queueing Agents with Tools
Named agents declaring their tools in Tools() can run through the existing queue:
await MathAgent.Make()
.Queue("Use sum to calculate 12 + 30.")
.OnQueue("ai");For the asynchronous example, the worker resolves WeatherAgent and GetWeatherTool from its own service scope:
await WeatherAgent.Make()
.BroadcastOnQueue(
"What is the temperature at latitude -6.2, longitude 106.8?",
new PrivateChannel("weather.1"))
.OnQueue("ai");The worker must load the same application and service-provider registrations. Tool instances and delegates are recreated by Tools(); they are not serialized into the queue payload. Runtime tool overrides through WithTools or UsingTools are rejected when queueing. See Queues and Broadcasting for completion events and channel setup.
Testing Tool Calls
Fake the model's tool-call request and its final answer to exercise the real handler without contacting an AI provider. A plain fake text answer only tests the prompt; it does not exercise a tool.
This complete xUnit example assumes the application classes above are referenced by your test project:
using System.Text.Json;
using App.Ai.Agents;
using DotBlaze;
using Microsoft.Extensions.AI;
using Microsoft.Extensions.DependencyInjection;
using Xunit;
public sealed class MathAgentTests
{
[Fact]
public async Task Model_tool_call_executes_sum_and_returns_the_result()
{
using var services = new ServiceCollection().BuildServiceProvider();
await ServiceScope.Run(services, async () =>
{
var fake = MathAgent.Fake();
fake.Respond(new ChatResponse(new ChatMessage(ChatRole.Assistant,
[
new FunctionCallContent("call-1", "sum",
new Dictionary<string, object?> { ["a"] = 12, ["b"] = 30 }),
])));
fake.Respond(input =>
{
var result = Assert.Single(input.Messages
.SelectMany(message => message.Contents)
.OfType<FunctionResultContent>());
Assert.Equal("call-1", result.CallId);
Assert.Equal(42, JsonSerializer.SerializeToElement(result.Result).GetInt32());
return new ChatResponse(new ChatMessage(ChatRole.Assistant, "42"));
});
var response = await MathAgent.Make().Prompt("Use sum to calculate 12 + 30.");
Assert.Equal("42", response.Text);
Assert.Equal(2, fake.Calls.Count);
MathAgent.AssertPromptedTimes(1);
});
}
}The test needs no AI credentials or conversation database because the model is faked and the agent does not remember a conversation. There are two underlying model calls but one agent invocation. For HTTP-backed tools, also replace the HTTP handler or injected service in the test container: an AI fake still executes the real tool.
MCP Tools
The official ModelContextProtocol client SDK exposes McpClientTool as an AIFunction, so its tools work directly:
// mcp is a connected ModelContextProtocol.Client.McpClient owned by your app.
var tools = await mcp.ListToolsAsync();
var response = await Ai.Agent("Use the available knowledge tools.")
.WithTools(tools)
.Prompt("Find the release notes.");Keep the MCP client alive until generation finishes. Install the MCP client SDK in the application when using it; DotBlaze.AI does not bundle an MCP server.
Streaming
await foreach (var update in Ai.Agent().Stream("Explain embeddings."))
Console.Write(update.Text);Updates are .NET ChatResponseUpdate objects: inspect Contents for text, tool calls, results, and usage. In an ASP.NET Core endpoint, use the platform's SSE result:
return TypedResults.ServerSentEvents(
Ai.Agent().Stream(prompt, cancellationToken: httpContext.RequestAborted));For remembered streams, the agent's ConversationId becomes available after full enumeration.
Stream returns an AgentStream. Chain Then to run code after the stream completes and the conversation is stored, and Catch to observe a failure before it propagates. Collect() consumes the stream and returns the aggregated AgentResponse:
return SalesCoach.Make().ForUser(userId)
.Stream(prompt, cancellationToken: httpContext.RequestAborted)
.Then(async response => await Usage.Record(userId, response.Usage))
.Catch(error => logger.LogWarning(error, "Stream failed."))
.UsingVercelDataProtocol();
var full = await Ai.Agent().Stream("Explain embeddings.").Collect();Callbacks run only when the stream is fully enumerated; an abandoned or cancelled stream runs neither.
Vercel AI SDK and AG-UI
Return a protocol adapter from a minimal API or MVC controller:
return SalesCoach.Make()
.Stream(prompt, cancellationToken: httpContext.RequestAborted)
.UsingVercelDataProtocol();
// Or, for an AG-UI client:
return SalesCoach.Make()
.Stream(prompt, cancellationToken: httpContext.RequestAborted)
.UsingAgentUserInteractionProtocol(threadId: conversationId, runId: runId);The adapters send SSE with text/reasoning start-delta-end events, tool input/results, step boundaries, and terminal success/error events. Vercel responses include x-vercel-ai-ui-message-stream: v1 and [DONE]. AG-UI responses include RUN_STARTED and RUN_FINISHED or RUN_ERROR. Usage and citations use Vercel data-* events or AG-UI CUSTOM events. Exceptions produce a generic error rather than exposing provider details; disconnects cancel enumeration. These are output adapters: the application reads/validates the frontend request and supplies its prompt/history. Optional message/thread/run IDs describe the frontend protocol and do not authorize database conversation access.
Images, Audio, and Retrieval
Use a feature's entry point, configure it fluently, and await generation:
var image = await Image.Of("A mountain at sunrise")
.Quality("high").Landscape().Timeout(120)
.Generate(provider: "openai");
await image.StoreAs("sunrise.png");
var audio = await Audio.Of("Welcome back.")
.Voice("coral").Format("mp3").Instructions("Speak warmly.")
.Generate();
await audio.StoreAs("welcome.mp3");
var transcript = await Transcription.FromStorage("meeting.wav")
.Language("en").Generate();
var embeddings = await Embeddings.For(["first text", "second text"])
.Dimensions(1536).Generate();
var ranked = await Reranking.Of(documents).Limit(3)
.Rerank("installation", provider: "cohere");
Console.WriteLine(transcript.Text);
Console.WriteLine(embeddings.Embeddings[0].Length);
Console.WriteLine(ranked.First().Document);Responses expose Images/FirstImage(), Audio, Text, Embeddings, or Results, as appropriate. All generation responses also have Value, Provider, Model, and nullable Usage.
Image builders support Square, Portrait, Landscape, Size, Count, and Quality. Audio builders support Voice, Format, and Instructions. Transcription accepts FromPath, FromStorage, FromUpload, or FromBytes(bytes, filename). Embeddings are returned in input order, with counts, indexes, dimensions, and finite values checked. Reranking preserves the original document and index beside its score.
All generation builders support Timeout(seconds) for a deadline covering input loading and generation. Caller cancellation also propagates. Use the Generate(AiOptions) / Rerank(query, AiOptions) overloads for failover.
Image and audio responses provide Store() with a generated filename and StoreAs(path, disk) using DotBlaze's filesystem. Image storage requires inline Data; provider URLs must be downloaded explicitly.
Reference images and speaker transcripts
Reference images use the same inline DataContent type as chat:
var reference = new DataContent(await File.ReadAllBytesAsync("photo.png"), "image/png");
var edited = await Image.Of("Make the background blue.")
.Attachments(reference).Generate(provider: "openai");
await edited.Store();
var meeting = await Transcription.FromStorage("meeting.wav").Diarize()
.Generate(provider: "openai", model: "gpt-4o-transcribe-diarize");
foreach (var segment in meeting.Segments)
Console.WriteLine($"{segment.Start:F1}-{segment.End:F1} {segment.Speaker}: {segment.Text}");OpenAI reference images use multipart images/edits; PNG, JPEG, and WebP are accepted. Diarize uses diarized_json and automatic chunking, retains the plain Text, and adds speaker/start/end segments. A configured transcription model overrides the built-in default, so select a diarization-capable model explicitly when configuration normally uses Whisper. OpenAI-compatible endpoints must implement these operations; Gemini does not implement speaker diarization.
Mistral transcription
The mistral driver supports Transcription.FromPath(...).Generate(...) and .Diarize().Generate(...) using voxtral-mini-latest by default (override models:transcription as needed). Requests use multipart audio/transcriptions; diarization requests segment timestamps and preserves speaker IDs, start/end times, and text. A supplied language must be a two-letter ISO code. Missing speakers or invalid timestamps cause an error instead of fabricated transcript metadata. The configured model must support the requested operation.
Native Gemini media
var image = await Image.Of("A mountain").Landscape().Generate(provider: "gemini");
var edited = await Image.Of("Make the background blue.").Attachments(reference)
.Generate(provider: "gemini");
var speech = await Audio.Of("Welcome.").Voice("Kore").Format("wav")
.Generate(provider: "gemini");
var text = await Transcription.FromStorage("meeting.wav").Generate(provider: "gemini");Use a gemini driver provider configured with models supporting generateContent for the respective operation. Images support square/portrait/landscape aspect ratios, one image request, and automatic quality. Speech supports pcm or wav (set the format explicitly). Models that return raw PCM get a WAV header matching their sample rate; models that return WAV (such as gemini-3.8-flash-tts) are passed through unchanged, including their provenance chunk, or reduced to their samples for pcm. A response that finishes without audio raises an error naming Gemini's finishReason. The default voice maps to Kore. MP3 encoding and image quality levels are rejected rather than silently ignored.
Multimodal embeddings and caching
Each content group produces one vector, retaining input order:
var vectors = await Embeddings.ForContents(
[
[new TextContent("A cat"), reference],
[new TextContent("A dog")],
]).Dimensions(768).Cache(TimeSpan.FromHours(1))
.Generate(provider: "gemini", model: "gemini-embedding-2");
// One vector for one combined text/image input:
var single = await Embeddings.ForContent(new TextContent("A cat"), reference)
.Generate(provider: "gemini", model: "gemini-embedding-2");Text, inline media, and provider-readable media URIs are accepted by multimodal Gemini models, within the model's input limits. OpenAI embeddings remain text-only. Returned vector counts, dimensions, and finite values are checked.
Both text and multimodal embedding builders support Cache(duration, store: "redis"); omitting store uses DotBlaze's default cache. Cache keys hash the provider configuration/account, model, dimensions, and inputs. Cache hits set Cached = true, have no billable Usage, and do not emit a provider usage event. Use a shared cache store when results should be reused across workers. Strict AI fakes bypass the real manager/cache pipeline.
Files and Vector Stores
var file = await Files.Document.FromString("The refund period is 30 days.")
.As("notes.txt").Put(provider: "openai");
var store = await Stores.Create("Knowledge", provider: "openai");
await store.Add(file.Id);
var status = await Stores.Get(store.Id, provider: "openai");
if (status.Ready)
{
var matches = await status.Search("refund policy");
}
await store.Remove(file.Id);
await file.Delete();
await store.Delete();Indexing is asynchronous at the provider: inspect store status before searching. Each match includes its file ID, filename, text, and score.
Gemini providers support uploads (Put), Get, and Delete through the Gemini Files API, and file search stores through Stores.Create, Get, Delete, and store.Add(fileId, attributes:) (which imports the uploaded file; attributes become customMetadata). Gemini cannot download uploaded files, remove a file from a store by file ID, or search a store directly: search it from an agent with HostedFileSearchTool and the store's fileSearchStores/... name. Create the store first, then add files.
Files.Document supports FromPath, FromStorage, FromUpload, FromBytes, and FromString. Use As(filename) and Purpose(value) before Put(). Retrieve an existing file with Files.Document.FromId(id).Get(provider: ...), or call Download / Delete on that reference.
Pass provider-specific upload fields with WithProviderOptions (OpenAI, Azure, and OpenAI-compatible drivers):
var file = await Files.Document.FromPath("training.jsonl")
.Purpose("fine-tune")
.WithProviderOptions(new Dictionary<string, object?>
{
["expires_after"] = new Dictionary<string, object?>
{
["anchor"] = "created_at",
["seconds"] = 3600
}
})
.Put(provider: "openai");Purpose remains available and defaults to "assistants". An explicit purpose in WithProviderOptions overrides it regardless of method order. Each WithProviderOptions call replaces the previous options. For low-level requests, set UploadAiFile.ProviderOptions.
Options are sent as multipart fields: nested objects use bracket keys (expires_after[seconds]), arrays use indexed keys, booleans/numbers use JSON scalar formatting, and null becomes an empty field. Empty objects/arrays are rejected rather than silently omitted. file and filename are reserved, including bracket-prefixed variants: use the source methods and As instead. Other fields are forwarded for the provider to validate; supported fields and values depend on its API. Gemini rejects nonempty upload options with NotSupportedException; uploads without options are unchanged. Provider callbacks are not supported.
store.Add(Files.Document.FromPath("manual.pdf")) uploads and attaches a document using the store's provider. Removing a file from a store does not delete the upload unless you pass deleteFile: true.
Store and uploaded-file instances retain their provider for subsequent operations. When starting from a remote ID, supply the provider/account that created it.
Attach file metadata and filter search results on the provider:
await store.Add(file.Id, attributes: new Dictionary<string, object> { ["tenant"] = "a", ["year"] = 2026 });
var matches = await store.Search("refund policy", filter: new VectorSearchFilter("tenant", "a"));Filters support eq, ne, gt, gte, lt, and lte. Metadata values are numbers, booleans, or strings up to 512 characters, with at most 16 file attributes. Filters are sent as provider-side filters, not applied after retrieval. The same ToProviderFilter() representation can be used with HostedFileSearchTool.
Vector Search
Embeddings turn text into vectors whose distance reflects meaning. Store them next to your data and you can search your own database by meaning ("places to drink wine" finds "Napa Valley tasting rooms"), without a provider-hosted vector store. DotBlaze uses PostgreSQL's pgvector extension, as Laravel does.
| Laravel | DotBlaze |
|---|---|
Schema::ensureVectorExtensionExists() | Schema.EnsureVectorExtensionExists() |
$table->vector('embedding', dimensions: 1536)->index() | t.Vector("embedding", dimensions: 1536).Index() |
->whereVectorSimilarTo('embedding', $vector, minSimilarity: 0.4) | .WhereVectorSimilarTo("embedding", vector, minSimilarity: 0.4) |
->whereVectorSimilarTo('embedding', 'best wineries') | .WhereVectorSimilarTo("embedding", "best wineries") |
->selectVectorDistance('embedding', $vector, as: 'distance') | .SelectVectorDistance("embedding", vector, "distance") |
->orderByVectorDistance('embedding', $vector) | .OrderByVectorDistance("embedding", vector) |
Str::of('Napa Valley')->toEmbeddings() | await "Napa Valley".ToEmbeddings() |
SimilaritySearch::usingModel(Document::class, 'embedding') | SimilaritySearch.UsingModel<Document>(d => d.Embedding) |
Storing Embeddings
Enable the extension and add a Vector column in a migration. Its dimensions must match the embedding model's output (or the Dimensions(...) you request):
[Migration("2026_01_01_000000_create_documents_table")]
public sealed class CreateDocumentsTable : Migration
{
public override void Up()
{
Schema.EnsureVectorExtensionExists();
Schema.Create("documents", t =>
{
t.Id();
t.ForeignId("team_id");
t.String("title");
t.Text("body");
t.Boolean("published").Default(false);
t.Vector("embedding", dimensions: 1536).Nullable().Index();
t.Timestamps();
});
}
public override void Down() => Schema.DropIfExists("documents");
}On PostgreSQL the column is vector(1536), and .Index() creates an HNSW index with vector_cosine_ops, which the cosine-distance queries below use. Creating the extension needs a database user allowed to run CREATE EXTENSION, and the pgvector package installed on the server (for example the pgvector/pgvector Docker image).
The model property is a float[]. Mark it [Hidden] so it is not serialized with the model:
public class Document : Model<Document>
{
public long Id { get; set; }
[Fillable] public long TeamId { get; set; }
[Fillable] public string Title { get; set; } = "";
[Fillable] public string Body { get; set; } = "";
public bool Published { get; set; }
[Hidden] public float[]? Embedding { get; set; }
public DateTime? CreatedAt { get; set; }
public DateTime? UpdatedAt { get; set; }
}
var document = await Document.Create(new { TeamId = teamId, Title = "Napa Valley", Body = body });
document.Embedding = await $"{document.Title}\n{document.Body}".ToEmbeddings(dimensions: 1536);
await document.Save();DB.Table accepts a float[] value too: DB.Table("documents").Insert(new { title, body, embedding = vector }). Rows read with DB.Table(...).Get() return the column as float[]. Generating embeddings in a queued job keeps slow provider calls out of the request.
Querying by Similarity
WhereVectorSimilarTo keeps rows whose cosine similarity to the vector is at least minSimilarity (default 0.6; 1 is identical) and orders them most similar first. Pass order: false to keep your own ordering:
float[] vector = await "best wineries in Napa".ToEmbeddings();
var documents = await DB.Table("documents")
.Select("id", "title")
.SelectVectorDistance("embedding", vector) // adds a "distance" column
.Where("published", true)
.WhereVectorSimilarTo("embedding", vector, minSimilarity: 0.4)
.Limit(10)
.Get();| Method | SQL (pgvector) |
|---|---|
WhereVectorSimilarTo(column, vector, minSimilarity = 0.6, order = true) | 1 - (column <=> ?::vector) >= ?, then ORDER BY column <=> ?::vector |
OrWhereVectorSimilarTo(...) | The same, joined with OR |
WhereVectorDistanceLessThan(column, vector, maxDistance) | (column <=> ?::vector) <= ? |
OrWhereVectorDistanceLessThan(...) | The same, joined with OR |
SelectVectorDistance(column, vector, as = "distance") | Adds (column <=> ?::vector) AS distance; keeps table.* when nothing else is selected |
OrderByVectorDistance(column, vector) | ORDER BY (column <=> ?::vector) ASC |
Distances are cosine distances: 0 for the same direction, 1 for unrelated, 2 for opposite; similarity is 1 - distance. Vectors are sent as bound parameters ([0.1,0.2,...] cast with ::vector), never written into the SQL.
Model queries take the property instead of the column name:
var documents = await Document.Query()
.Where(d => d.TeamId == teamId)
.WhereVectorSimilarTo(d => d.Embedding, vector, minSimilarity: 0.5)
.Take(10)
.Get();Query<T> also has WhereVectorDistanceLessThan and OrderByVectorDistance. In your own LINQ, VectorSql.CosineDistance(d.Embedding, vector) translates to embedding <=> @p::vector.
Searching with Text
Pass a string instead of a vector and it is embedded with the default embeddings provider. On DB.Table, the string is embedded once, when the query runs, so the query still chains:
var matches = await DB.Table("documents")
.WhereVectorSimilarTo("embedding", "best wineries in Napa", minSimilarity: 0.4)
.Limit(10)
.Get();EF Core needs the vector before it builds the query, so the model variant is awaited first:
var query = await Document.Query().WhereVectorSimilarTo(d => d.Embedding, "best wineries in Napa");
var documents = await query.Take(10).Get();Choose the provider, model, dimensions, or a cache with EmbeddingOptions:
var embedding = new EmbeddingOptions(Provider: "openai", Model: "text-embedding-3-small", Dimensions: 1536, Cache: TimeSpan.FromDays(1));
var matches = await DB.Table("documents").WhereVectorSimilarTo("embedding", search, embedding: embedding).Get();The same options are available on the string helpers, which return the vector:
float[] vector = await "Napa Valley has great wine.".ToEmbeddings();
float[] cached = await Str.Of(input).Trim().ToEmbeddings(dimensions: 1536, cache: TimeSpan.FromHours(1), provider: "openai");Searches repeat, so caching the query embedding (Cache: ...) saves a provider call per repeated search; see embedding caching.
The SimilaritySearch Tool
SimilaritySearch is an agent tool that lets the model search your data. The model calls it with a query string; the tool embeds the query, runs the vector query, and returns the matches as JSON:
using DotBlaze.ArtificialIntelligence;
using Microsoft.Extensions.AI;
public sealed class SupportAgent(long teamId) : Agent<SupportAgent>
{
public override string Instructions { get; init; } =
"Answer from the knowledge base. Search it before answering.";
public override IEnumerable<AITool> Tools() =>
[
SimilaritySearch.UsingModel<Document>(d => d.Embedding, minSimilarity: 0.5, limit: 5,
constrain: q => q.Where(d => d.TeamId == teamId))
.WithDescription("Search the team's help-center articles."),
];
}Models are serialized with their serialization rules ([Hidden], [Visible], [Appends]), and the vector property is always left out. For a table without a model, SimilaritySearch.UsingTable("documents", "embedding", minSimilarity: 0.5, limit: 5, constrain: q => q.Where("published", true)) returns each row with its distance, without the vector column.
Use a closure for any other search (another connection, a hybrid keyword search, an external index, or databases without pgvector):
SimilaritySearch.Using(async (query, cancellationToken) =>
{
var vector = await query.ToEmbeddings(cancellationToken: cancellationToken);
return await Document.Query().WhereVectorSimilarTo(d => d.Embedding, vector).Take(5).Get();
}).WithDescription("Search the product manuals.");The tool is named similarity_search (change it with WithName), and its default description asks the model to search by meaning. Give each instance a description that says what is searchable. When nothing matches, the model receives No matching results.. UsingModel, UsingTable, and Using accept EmbeddingOptions (UsingModel/UsingTable) or your own embedding call (Using).
Test it like any tool: fake the chat with Ai.Fake() first, then the query embedding with Embeddings.Fake(...) (Ai.Fake() replaces feature fakes installed before it):
var fake = Ai.Fake();
Embeddings.Fake((IReadOnlyList<float[]>)[[0.9f, 0.1f]]);
fake.Respond(new ChatResponse(new ChatMessage(ChatRole.Assistant,
[new FunctionCallContent("call-1", "similarity_search", new Dictionary<string, object?> { ["query"] = "wine" })])));
fake.Respond("Visit Napa.");Other Databases and Limitations
SQLite, MySQL, and SQL Server have no native vector type.
t.Vector(...)creates a text column that holds the vector as a JSON array ([0.1,0.2]),EnsureVectorExtensionExists()and.Index()on it do nothing, andfloat[]values passed toDB.Tableare stored as that JSON. The vector query methods throwNotSupportedException. For small tables, rank in memory:csharpusing DotBlaze.Support; var vector = await "best wineries".ToEmbeddings(); var rows = await DB.Table("documents").Get(); var best = rows.RankBySimilarity(r => VectorMath.Parse((string)r["embedding"]!), vector, minSimilarity: 0.5, limit: 10); foreach (var match in best) Console.WriteLine($"{match.Item["title"]} {match.Similarity:F2}");VectorMathalso providesCosineSimilarity,CosineDistance,ToLiteral, andParse. On SQLite the model property can stayfloat[](EF Core stores it as JSON).Cosine distance only. Queries use pgvector's
<=>operator; L2 (<->) and inner product (<#>) are available throughWhereRaw/DB.Rawwith a bound?::vectorparameter.Model
SelectVectorDistanceis not available; useDB.Tablewhen you need the distance value.Extension types are loaded when the application first connects. If the
vectorextension is created while the application is running, restart it before reading vector columns.t.Vectorcolumns supportvector(up to 16,000 dimensions; HNSW indexes up to 2,000). Larger models can useDimensions(...)to shorten their output.
Queues and Broadcasting
await SalesCoach.Make()
.Queue("Review the latest transcript...", provider: "openai")
.OnQueue("ai");
await SalesCoach.Make()
.ForUser("12")
.BroadcastOnQueue("Review the latest transcript...", new PrivateChannel("users.12"))
.OnQueue("ai");The existing queue serializes instructions, explicit history, provider options, and conversation identity; the worker constructs a fresh agent from DI. Use Continue before queueing to continue a conversation. Agent constructor state is not serialized: queue agents whose constructor dependencies can be resolved by the worker. Declare queued tools in Tools(); runtime tool overrides are rejected because tool delegates cannot be serialized.
Queue dispatches AgentCompleted when finished. BroadcastOnQueue sends ai.update for each streamed update, then ai.completed containing the conversation ID. Terminal job failure sends ai.failed with a generic message. These use DotBlaze's broadcasting, including channel authorization and a backplane for separate workers. Handle completion through the event dispatcher, or attach handler classes:
public sealed class SaveReview(AppDbContext db) : IAgentResponseHandler
{
public async Task Handle(AgentResponse response) { /* ... */ }
}
public sealed class ReportFailure : IAgentFailureHandler
{
public Task Handle(Exception exception) { /* ... */ return Task.CompletedTask; }
}
await SalesCoach.Make().Queue("Review the transcript...")
.Then<SaveReview>().Catch<ReportFailure>().OnQueue("ai");Queue and BroadcastOnQueue accept a trailing chatOptions parameter. Temperature, output limits, reasoning, response format, and JSON-compatible extension values are snapshotted when dispatched; later changes to the original options do not change the job. Tools must still be declared in Tools(). Executable factories, custom option subclasses, non-JSON extension objects, and provider-managed background/history options are rejected.
For validated typed results:
await SalesCoach.Make().QueueStructured<Review>("Review this call...",
chatOptions: new() { Temperature = 0.2f, MaxOutputTokens = 1000 })
.Then<Review, SaveTypedReview>().OnQueue("ai");
await SalesCoach.Make().QueueClassify("Great service!", ["positive", "negative"])
.Then<string, SaveLabel>().OnQueue("ai");
public sealed class SaveTypedReview : IAgentResponseHandler<Review>
{
public Task Handle(StructuredAgentResponse<Review> result)
{
// Persist result.Value using your application's services.
return Task.CompletedTask;
}
}
public sealed class SaveLabel : IAgentResponseHandler<string>
{
public Task Handle(StructuredAgentResponse<string> result) => Task.CompletedTask;
}Typed jobs emit both AgentCompleted and AgentCompleted<T> after validation and persistence. Existing untyped handlers continue to receive the underlying response. Typed handler result types are checked before dispatch. Invalid structured output or labels fail without storing the turn; typed results are not broadcast as unvalidated partial output. Queue workers preserve context turn limits and estimated token budgets.
Closures cannot be serialized into a queue payload, so Then<T>/Catch<T> store handler type names; the worker creates them through DI. Then handlers run after the response (or broadcast stream) completes; Catch handlers run when the job fails for good, after its retries.
Retries, Failover, and Usage
Before failing over, each built-in provider retries its own rate-limited or temporarily failing requests: status 408, 429, 500, 502, 503, 504, and 529, plus connection failures. Retries wait for the provider's Retry-After (or retry-after-ms) header or Google's RetryInfo.retryDelay in the error body, otherwise use exponential backoff with jitter. A spent daily quota (Gemini asks to wait hours) therefore fails immediately instead of retrying. Configure them per provider:
openai = new
{
driver = "openai", key = Env("OPENAI_API_KEY"),
retry = new { times = 2, delay = 1, max_delay = 30 }, // the defaults; times = 0 disables retries
},times is the number of extra attempts (0 to 10), delay the base backoff in seconds (doubled per attempt), and max_delay the longest wait in seconds. When a provider asks to wait longer than max_delay, the SDK does not wait: the error is raised immediately so failover, or your queue's own retry, can take over. Retries share the request's HTTP timeout, and caller cancellation stops a pending wait.
Only failures before a response starts are retried, so streamed output is never replayed. Requests that create remote state (file uploads, store creation and file attachment, OpenAI stored or background responses and conv_... conversations) are retried only after 429, which means the provider rejected them; a 5xx there might have been processed, so it is raised instead. Polling, stream resumption, reads, searches, and deletes by ID are retried normally. Custom IAiGateway, IChatClient, and IAiGenerator registrations handle their own retries.
var response = await Ai.Agent().Prompt("Summarize this...",
new AiOptions("openai", Failover: [new AiProviderChoice("local", "llama3.2")]));Once a provider's retries are exhausted, failover handles connection errors, HTTP timeouts, and status codes 408, 429, and 5xx. Authentication errors, invalid requests, and caller cancellation propagate. Fallbacks use their own model configuration unless explicitly overridden.
Streams can fail over only before their first update, avoiding duplicate output or tool execution. Files and vector-store operations never fail over, because their IDs and mutations belong to one provider.
Usage is available on responses when supplied by the provider. Observe successful underlying requests with:
Instrumentation.Listen<AiUsageRecorded>(usage =>
Log.Info($"AI {usage.Provider}/{usage.Operation}: {usage.Usage?.TotalTokenCount} tokens"));Events include model and duration; each tool-loop model call has its own event. They do not automatically persist billing records.
Configure prices per million tokens under a provider's pricing (keyed by model, with input, output, and optional cached_input) to get AiUsageRecorded.Cost. Estimate a response's cost directly with Ai.EstimateCost("anthropic", response.Response.ModelId, response.Usage). Costs are estimates from your configured prices in your chosen currency; check the provider's invoice for billing.
Events
The SDK dispatches events through DotBlaze's event dispatcher, so listeners, queued listeners, and Event.Fake() work as usual:
| Event | When |
|---|---|
PromptingAgent / AgentPrompted | Before and after Prompt, Structured<T>, and classification |
StreamingAgent / AgentStreamed | Before a stream starts and after it completes |
InvokingTool / ToolInvoked | Around each local function or MCP tool call, with arguments and result |
GeneratingImage / ImageGenerated | Image generation |
GeneratingAudio / AudioGenerated | Speech generation |
GeneratingTranscription / TranscriptionGenerated | Transcription, including diarized |
GeneratingEmbeddings / EmbeddingsGenerated | Embeddings, including cache hits |
RerankingDocuments / Reranked | Reranking |
StoringFile / FileStored, CreatingStore / StoreCreated | File uploads and vector store creation |
Event.Listen<ToolInvoked>(e => Log.Info($"{e.Agent} called {e.Tool}"));Agent events carry the agent's type name and an InvocationId shared by all events of one prompt (also on AgentResponse.InvocationId). Generation events are dispatched by the fluent builders and Ai.Generate; calls made directly on an injected IAi dispatch only AiUsageRecorded. Events are skipped outside an application scope. Provider-hosted tool calls run on the provider and do not raise tool events.
Testing
Inside a DotBlaze service scope:
SalesCoach.Fake("A scripted answer.");
var response = await SalesCoach.Make().Prompt("Help me.");
SalesCoach.AssertPrompted("Help me.");
SalesCoach.AssertPromptedTimes(1);
SalesCoach.AssertNotPrompted("Something else.");
Image.Fake(imageBytes);
await Image.Of("sunrise").Landscape().Generate();
Image.AssertGenerated(prompt => prompt.Prompt.Contains("sunrise") && prompt.Size == "1536x1024");
Embeddings.Fake((IReadOnlyList<float[]>)[new float[] { 0.1f, 0.2f }]);
var embeddings = await Embeddings.For(["hello"]).Dimensions(2).Generate();
Embeddings.AssertGenerated(prompt => prompt.Dimensions == 2);Each named agent and feature has an independent fake. Audio, Transcription, Embeddings, and Reranking accept their typed responses in Fake(...); Classification.Fake(...) accepts labels. Use AssertGenerated / AssertNotGenerated / AssertNothingGenerated for media, AssertReranked for reranking, and AssertClassified for classification.
Files.Fake() and Stores.Fake() return a recorder on which you script typed responses with Respond(...). Stores.Fake() also installs a file fake. File assertions include AssertStored and AssertDeleted; store assertions include AssertCreated, AssertDeleted, and instance-level AssertAdded / AssertRemoved.
The returned AiFake also supports Respond(ChatResponse) for tool calls, Respond(Func<AiChatInput, ChatResponse>) to inspect chat input, and RespondStream(...). Each scripted response is consumed once; all fakes are strict, including Fake() with no responses. Unscripted requests throw without network access.
Ai.Fake(...) fakes the whole SDK. Calls captures provider requests and Prompts captures agent invocations (one entry per prompt, including a tool loop). Fakes are isolated per async flow. For constructor-injected code, register an AiFake as IAi in the test container.
Live provider tests. The framework's own suite includes AiLiveOpenAiTest.cs and AiLiveGeminiTest.cs, which exercise prompts, streaming, tools, structured output, classification, stored conversations, reasoning, embeddings, speech and transcription, images, files and vector stores, remote history, background responses, and hosted web search against the real provider APIs. They are skipped unless explicitly enabled, because they cost money:
DOTBLAZE_LIVE_AI=1 OPENAI_API_KEY=sk-... dotnet test tests/DotBlaze.Tests --filter "FullyQualifiedName~AiLiveOpenAiTest"
DOTBLAZE_LIVE_AI=1 GEMINI_API_KEY=... dotnet test tests/DotBlaze.Tests --filter "FullyQualifiedName~AiLiveGeminiTest"Each test runs only when its provider's key is set. Gemini's free tier allows about 20 requests per model per day and none for image generation or Google Search grounding; set DOTBLAZE_LIVE_GEMINI_MODEL to another model when one model's quota is spent, and use a billing-enabled key for the image and search tests.
Provider HTTP failures raise HttpRequestException with the status code and the provider's error message (for example 400 (Bad Request). The model 'x' does not exist.), so failover still sees the status while logs stay diagnosable.
Complete Example: Authenticated Assistant
Start with the Blog application, including make:auth. Install DotBlaze.AI, add the AiConfig from configuration using namespace Blog.Configuration, supply the selected provider's environment key, and run dotblaze migrate.
Use a namespace such as Blog.Intelligence for application code. If you use Blog.Ai, that namespace can shadow the Ai facade in other Blog.* code; qualify calls as global::DotBlaze.Ai.Agent() in that case.
// app/Intelligence/DocumentationAssistant.cs
using DotBlaze.ArtificialIntelligence;
namespace Blog.Intelligence;
public sealed class DocumentationAssistant : Agent<DocumentationAssistant>
{
public override string Instructions { get; init; } =
"Help the user understand their notes. State when information is missing.";
}// app/Http/Requests/AssistantRequest.cs
using DotBlaze;
using FluentValidation;
namespace Blog.Requests;
public class AssistantRequest : FormRequest<AssistantRequest>
{
public string Prompt { get; set; } = "";
public string? ConversationId { get; set; }
public override void Rules(RuleSet<AssistantRequest> rules)
{
rules.Field(value => value.Prompt).NotEmpty().MaximumLength(4000);
rules.Field(value => value.ConversationId).MaximumLength(200);
}
}// app/Http/Controllers/AssistantController.cs
using Blog.Intelligence;
using Blog.Requests;
using DotBlaze;
using Microsoft.AspNetCore.Mvc;
namespace Blog.Controllers;
public class AssistantController : BaseController
{
public IActionResult Create() => View();
public async Task<IActionResult> Store(AssistantRequest request)
{
var owner = $"{Auth.Id()}";
var conversation = string.IsNullOrWhiteSpace(request.ConversationId)
? null : request.ConversationId;
try
{
var response = await DocumentationAssistant.Make()
.ContinueOrStart(conversation, owner)
.Prompt(request.Prompt, cancellationToken: HttpContext.RequestAborted);
return Json(new { response.Text, response.ConversationId });
}
catch (KeyNotFoundException)
{
return NotFound(new { message = "Conversation not found." });
}
}
}Inside the existing Web.Map():
Route.Get<Blog.Controllers.AssistantController>("/assistant", c => c.Create)
.Name("assistant.create").Middleware("auth");
Route.Post<Blog.Controllers.AssistantController>("/assistant", c => c.Store)
.Name("assistant.store").Middleware("auth", "throttle:10,1,assistant");<!-- resources/views/assistant/Create.blade.html -->
@extends('layouts.app')
@section('content')
<form method="post" action="{{ Route('assistant.store') }}">
@csrf
<label for="prompt">Your question</label>
<textarea id="prompt" name="Prompt" maxlength="4000" required>{{ Old('Prompt') }}</textarea>
<p role="alert">{{ Error('Prompt') }}</p>
<label for="conversation">Conversation ID (empty starts a conversation)</label>
<input id="conversation" name="ConversationId" maxlength="200" />
<button type="submit">Ask assistant</button>
</form>
@endsectionRun dotblaze serve, sign in, and visit /assistant. Submitting returns JSON with text and conversationId. Copy that ID into a later request to continue. A different user's conversation returns 404 before generation. Use the authenticated user's numeric ID; never accept a user ID from the form.
Provider text varies. Invalid credentials, network failures, and invalid provider responses are real errors; this example lets the framework report them rather than returning a fabricated successful answer. For streaming, add this independent-prompt action to the same controller:
public async Task Stream(AssistantRequest request)
{
var updates = DocumentationAssistant.Make().Stream(
request.Prompt, cancellationToken: HttpContext.RequestAborted);
await Microsoft.AspNetCore.Http.TypedResults.ServerSentEvents(updates)
.ExecuteAsync(HttpContext);
}Register it inside Web.Map():
Route.Post<Blog.Controllers.AssistantController>("/assistant/stream", c => c.Stream)
.Name("assistant.stream").Middleware("auth", "throttle:10,1,assistant");A fetch client must send the form token and consume the text/event-stream response; cancelling that request propagates to generation. This action does not use ConversationId. Remembered streams require full enumeration before the completed turn is stored.
For queued agents, declare tools on the agent class, dispatch onto an explicit queue, and run dotblaze queue:work --connection=database --queue=ai. A separate worker needs the same provider configuration and database; broadcasts also need the backplane described in broadcasting.
Complete Offline Self-Check
After adding the assistant class above, this command needs neither an API key nor a migrated conversation table. It checks text and typed structured output with strict scripted responses:
// app/Commands/AiDemo.cs
using Blog.Intelligence;
using DotBlaze;
namespace Blog.Commands;
public record DocumentationSummary(string Topic, int Steps);
public class AiDemo : Command
{
public override string Signature => "demo:ai";
public override async Task<int> Handle()
{
DocumentationAssistant.Fake(
"Read the installation guide.",
"""{"Topic":"Installation","Steps":3}""");
var text = await DocumentationAssistant.Make().Prompt("Where should I start?");
var summary = await DocumentationAssistant.Make()
.Structured<DocumentationSummary>("Summarize the installation steps.");
if (text.Text != "Read the installation guide." ||
summary.Value.Topic != "Installation" || summary.Value.Steps != 3)
throw new InvalidOperationException("AI response self-check failed.");
DocumentationAssistant.AssertPrompted("Where should I start?");
DocumentationAssistant.AssertPromptedTimes(2);
Line($"{summary.Value.Topic}: {summary.Value.Steps} steps");
return 0;
}
}Run dotblaze demo:ai. Expected: Installation: 3 steps. A third unscripted prompt throws rather than reaching a provider. This verifies application wiring and deserialization, not the accuracy of a real model. See tool-call testing for scripted tool calls and results, and AiFluentTest.cs for executable coverage of the fluent API.