> For the complete documentation index, see [llms.txt](https://docs.umbraco.com/llms.txt). Markdown versions of documentation pages are available by appending `.md` to page URLs; this page is available as [Markdown](https://docs.umbraco.com/ai-in-umbraco/19.latest/reference/services/ai-chat-service.md).

# IAIChatService

Service for AI chat completions.

The primary service for performing chat completions. Acts as a thin layer over Microsoft.Extensions.AI, adding Umbraco-specific features like profiles and middleware.

## Namespace

{% code title="Namespace" %}

```csharp
using Umbraco.AI.Core.Chat;
using Umbraco.AI.Core.InlineChat;
using Microsoft.Extensions.AI;
```

{% endcode %}

## Interface

{% code title="IAIChatService" %}

```csharp
public interface IAIChatService
{
    Task<ChatResponse> GetChatResponseAsync(
        Action<AIChatBuilder> configure,
        IEnumerable<ChatMessage> messages,
        CancellationToken cancellationToken = default);

    IAsyncEnumerable<ChatResponseUpdate> StreamChatResponseAsync(
        Action<AIChatBuilder> configure,
        IEnumerable<ChatMessage> messages,
        CancellationToken cancellationToken = default);

    Task<IChatClient> CreateChatClientAsync(
        Action<AIChatBuilder> configure,
        CancellationToken cancellationToken = default);
}
```

{% endcode %}

## AIChatBuilder

All methods accept an `Action<AIChatBuilder>` to configure the request. The builder provides the following fluent methods:

| Method                                                                       | Description                                                   |
| ---------------------------------------------------------------------------- | ------------------------------------------------------------- |
| `.WithAlias(string alias)`                                                   | **Required.** Sets an alias for auditing and telemetry.       |
| `.WithName(string name)`                                                     | Sets a display name for telemetry purposes.                   |
| `.WithDescription(string? description)`                                      | Sets a description for telemetry purposes.                    |
| `.WithProfile(Guid profileId)`                                               | Selects a profile by ID. Uses default if omitted.             |
| `.WithProfile(string profileAlias)`                                          | Selects a profile by alias.                                   |
| `.WithChatOptions(ChatOptions options)`                                      | Overrides profile defaults for temperature, max tokens, etc.  |
| `.WithGuardrails(params Guid[] guardrailIds)`                                | Applies guardrails by ID.                                     |
| `.WithGuardrails(params string[] guardrailAliases)`                          | Applies guardrails by alias.                                  |
| `.WithContextItems(IEnumerable<AIRequestContextItem> contextItems)`          | Attaches context items to the request.                        |
| `.WithOutputSchema(AIOutputSchema schema)`                                   | Sets a structured output schema for the response.             |
| `.WithAdditionalProperties(IReadOnlyDictionary<string, object?> properties)` | Attaches additional properties to the request.                |
| `.AsPassThrough()`                                                           | Marks the request as pass-through (bypasses some processing). |

{% code title="Builder example" %}

```csharp
var response = await _chatService.GetChatResponseAsync(
    chat => chat
        .WithAlias("my-summarizer")
        .WithProfile("default-chat")
        .WithChatOptions(new ChatOptions { Temperature = 0.7f }),
    messages,
    cancellationToken);
```

{% endcode %}

## Methods

### GetChatResponseAsync

Performs a chat completion and returns the full response.

{% code title="Signature" %}

```csharp
Task<ChatResponse> GetChatResponseAsync(
    Action<AIChatBuilder> configure,
    IEnumerable<ChatMessage> messages,
    CancellationToken cancellationToken = default);
```

{% endcode %}

| Parameter           | Type                       | Description                                         |
| ------------------- | -------------------------- | --------------------------------------------------- |
| `configure`         | `Action<AIChatBuilder>`    | Builder action to set alias, profile, options, etc. |
| `messages`          | `IEnumerable<ChatMessage>` | The conversation messages                           |
| `cancellationToken` | `CancellationToken`        | Cancellation token                                  |

**Returns**: `ChatResponse` with the assistant's message, usage stats, and finish reason.

{% code title="Example" %}

```csharp
var messages = new[]
{
    new ChatMessage(ChatRole.System, "You are a helpful assistant."),
    new ChatMessage(ChatRole.User, "What is Umbraco?")
};

var response = await _chatService.GetChatResponseAsync(
    chat => chat.WithAlias("my-assistant"),
    messages);

Console.WriteLine(response.Message.Text);
Console.WriteLine($"Tokens: {response.Usage?.TotalTokenCount}");
```

{% endcode %}

### StreamChatResponseAsync

Performs a streaming chat completion, yielding updates as they arrive.

{% code title="Signature" %}

```csharp
IAsyncEnumerable<ChatResponseUpdate> StreamChatResponseAsync(
    Action<AIChatBuilder> configure,
    IEnumerable<ChatMessage> messages,
    CancellationToken cancellationToken = default);
```

{% endcode %}

| Parameter           | Type                       | Description                                         |
| ------------------- | -------------------------- | --------------------------------------------------- |
| `configure`         | `Action<AIChatBuilder>`    | Builder action to set alias, profile, options, etc. |
| `messages`          | `IEnumerable<ChatMessage>` | The conversation messages                           |
| `cancellationToken` | `CancellationToken`        | Cancellation token                                  |

**Returns**: `IAsyncEnumerable<ChatResponseUpdate>` yielding content chunks.

{% code title="Example" %}

```csharp
var messages = new[]
{
    new ChatMessage(ChatRole.User, "Write a story about a robot.")
};

await foreach (var update in _chatService.StreamChatResponseAsync(
    chat => chat.WithAlias("story-writer"),
    messages))
{
    Console.Write(update.Text);
}
```

{% endcode %}

### CreateChatClientAsync

Creates a configured `IChatClient` for advanced scenarios.

{% code title="Signature" %}

```csharp
Task<IChatClient> CreateChatClientAsync(
    Action<AIChatBuilder> configure,
    CancellationToken cancellationToken = default);
```

{% endcode %}

| Parameter           | Type                    | Description                                         |
| ------------------- | ----------------------- | --------------------------------------------------- |
| `configure`         | `Action<AIChatBuilder>` | Builder action to set alias, profile, options, etc. |
| `cancellationToken` | `CancellationToken`     | Cancellation token                                  |

**Returns**: Configured `IChatClient` with middleware applied.

{% code title="Example" %}

```csharp
// Create client for advanced usage
var client = await _chatService.CreateChatClientAsync(
    chat => chat.WithAlias("advanced-client").WithProfile("default-chat"));

// Use M.E.AI methods directly
var response = await client.GetResponseAsync(
    messages,
    new ChatOptions { Temperature = 0.5f });
```

{% endcode %}

## ChatOptions

Profile settings can be overridden via `ChatOptions`:

{% code title="ChatOptions" %}

```csharp
var options = new ChatOptions
{
    Temperature = 0.7f,
    MaxOutputTokens = 2000,
    StopSequences = new[] { "END" }
};

var response = await _chatService.GetChatResponseAsync(
    chat => chat
        .WithAlias("creative-chat")
        .WithChatOptions(options),
    messages);
```

{% endcode %}

## Related Types

* `ChatMessage` - Message in a conversation (M.E.AI)
* `ChatResponse` - Completion response (M.E.AI)
* `ChatResponseUpdate` - Streaming chunk (M.E.AI)
* `ChatOptions` - Request options (M.E.AI)


---

# Agent Instructions
This documentation is published with GitBook. GitBook is the documentation platform designed so that both humans and AI agents can read, navigate, and reason over technical content effectively. Learn more at gitbook.com.

## Querying This Documentation
If you need additional information that is not directly available in this page, you can query the documentation by asking a question.

Perform an HTTP GET request on the following URL with the `ask` and `goal` query parameters:

```
GET https://docs.umbraco.com/ai-in-umbraco/19.latest/reference/services/ai-chat-service.md?ask=<question>&goal=<user_goal>
```

`ask` is the immediate question: it should be specific, self-contained, and written in natural language.
`goal` is what the user is ultimately trying to achieve, the reason they need the answer. Sharing it helps GitBook give you a better, more relevant answer. A goal is most helpful when it describes the outcome the user wants rather than restating the question. For example, with `ask=how do I create an API token`, a goal like `automate deployments from our CI pipeline` lets GitBook tailor the answer to that use case.

The response will contain a direct answer to the question and relevant excerpts and sources from the documentation.

Use this mechanism when the answer is not explicitly present in the current page, you need clarification or additional context, or you want to retrieve related documentation sections.
