# Microsoft.Extensions.AI

Integration with [Microsoft.Extensions.AI](https://learn.microsoft.com/dotnet/ai/microsoft-extensions-ai) (`IChatClient`).

Before configuring this integration, prepare the [Agent Memory prerequisites](https://www.telerik.com/ai-observability-platform/documentation/agent-memory/getting-started#prerequisites).

## Installation

Install the Memory integration package:

```bash
dotnet add package Progress.Memory.Extensions.AI
dotnet add package Microsoft.Extensions.AI.OpenAI --version 10.6.0
dotnet add package OpenAI --version 2.10.0
```

The Memory package includes `Progress.Memory` as a transitive dependency.

Replace the backend URL, SDK API key, and LLM API key with your own values. The fixed user and agent identifiers are for a single-user example.

## Integration Modes

| Mode           | How it works                                                                                             | Best for                                                       |
| -------------- | -------------------------------------------------------------------------------------------------------- | -------------------------------------------------------------- |
| **Middleware** | Relevant memories are recalled before each invocation of the wrapped chat client.                        | Simple chat loops that require automatic memory recall.        |
| **Tools**      | Adds `remember`, `recall`, and `forget` as callable tool functions. The LLM decides when to invoke them. | Agent workflows that let the LLM decide when to access memory. |

## Recall Options

The following option applies to `UseProgressMemory()` and `WithProgressMemoryTools()` overloads that accept a memory client. It is also available on `ProgressMemoryInjectingChatClient` and `ProgressMemoryAIFunctions.CreateRecallFunction()`.

| Parameter                  | Type   | Default | Purpose                                                                                                                                                                                                                                    |
| -------------------------- | ------ | ------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ |
| `includeOutdatedByDefault` | `bool` | `false` | Optional. If omitted, recalls only active memories. Set to `true` to also recall outdated memories. See [memory status](https://www.telerik.com/ai-observability-platform/documentation/agent-memory/overview#status-active-and-outdated). |

## Middleware Mode — Recall Only (Default)

The following example adds memory recall to an OpenAI chat client without automatically saving the exchange:

```cs
using Microsoft.Extensions.AI;
using OpenAI;
using Progress.Memory;
using Progress.Memory.Extensions.AI;

var llmApiKey = "your-llm-api-key";
var llmModel = "gpt-4.1";
var memoryClient = ProgressMemoryClient.Create(new ProgressMemoryConfig(
  BackendBaseUrl: "https://memory-api.observability.progress.com",
  SdkApiKey:      "pmem_d_..."));

var baseChatClient = new OpenAIClient(llmApiKey).GetChatClient(llmModel).AsIChatClient();
IChatClient client = baseChatClient
    .AsBuilder()
    .UseProgressMemory(
        memoryClient, userId: "user-123", agentId: "support-bot",
        includeOutdatedByDefault: false) // Optional; omit for active-only retrieval.
    .Build();

var response = await client.GetResponseAsync(
    "What display preferences do you remember about me?");
```

## Middleware Mode — Recall + Auto-Remember

Set `autoRemember: true` to save each user and assistant exchange after the model responds.

The adapter API depends on the Microsoft.Extensions.AI.OpenAI package version. Newer package versions use the AsIChatClient() adapter pattern described in the [`Microsoft.Extensions.AI documentation`](https://learn.microsoft.com/en-gb/dotnet/ai/microsoft-extensions-ai), whereas older versions exposed OpenAIChatClient directly. The examples below use the newer GetChatClient(...).AsIChatClient() pattern available in recent package versions.

```cs
using Microsoft.Extensions.AI;
using OpenAI;
using Progress.Memory;
using Progress.Memory.Extensions.AI;

var openAiClient = new OpenAIClient("your-llm-api-key");
var memoryClient = ProgressMemoryClient.Create(new ProgressMemoryConfig(
  BackendBaseUrl: "https://memory-api.observability.progress.com",
  SdkApiKey:      "pmem_d_..."));

// Adapt the OpenAI SDK ChatClient to Microsoft.Extensions.AI's IChatClient.
IChatClient baseChatClient = openAiClient
    .GetChatClient("gpt-4.1")
    .AsIChatClient();

IChatClient client = baseChatClient
    .AsBuilder()
    .UseProgressMemory(
        memoryClient,
        userId:       "user-123",
        agentId:      "support-bot",
        topK:         10,      // number of memories to inject per request (default 10)
        autoRemember: true)    // save every exchange automatically (default false)
    .Build();
```

## Middleware Mode — With Dependency Injection

Register the memory client and chat client with dependency injection:

```cs
using Microsoft.Extensions.AI;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using OpenAI;
using Progress.Memory.Extensions;
using Progress.Memory.Extensions.AI;

var services = new ServiceCollection();
var configuration = new ConfigurationBuilder()
  .AddEnvironmentVariables()
  .Build();

// Register the core client
services.AddProgressMemory(configuration);

// Register the chat client with memory middleware
services.AddChatClient(serviceProvider =>
    new OpenAIClient("your-llm-api-key")
        .GetChatClient("gpt-4.1")
        .AsIChatClient()
        .AsBuilder()
        .UseProgressMemory(
            serviceProvider,
            userId: "user-123",
            agentId: "support-bot",
            autoRemember: true)
        .Build());

var serviceProvider = services.BuildServiceProvider();
var client = serviceProvider.GetRequiredService<IChatClient>();
```

The SDK reads `PROGRESS_MEMORY_BACKEND_URL` and `PROGRESS_MEMORY_SDK_API_KEY` from `configuration`, which includes environment variables.

## Tools Mode

Add `remember`, `recall`, and `forget` tools to `ChatOptions` so the LLM can control memory access itself.

```cs
using Microsoft.Extensions.AI;
using OpenAI;
using Progress.Memory;
using Progress.Memory.Models;
using Progress.Memory.Extensions.AI;

var llmApiKey = "your-llm-api-key";
var llmModel = "gpt-4.1";
var memoryClient = ProgressMemoryClient.Create(new ProgressMemoryConfig(
  BackendBaseUrl: "https://memory-api.observability.progress.com",
  SdkApiKey:      "pmem_d_..."));

var baseChatClient = new OpenAIClient(llmApiKey).GetChatClient(llmModel).AsIChatClient();
var messages = new List<ChatMessage>
{
  new(ChatRole.User, "What do you know about my preferences?")
};

var options = new ChatOptions()
    .WithProgressMemoryTools(
        memoryClient, userId: "user-123", agentId: "support-bot",
        includeOutdatedByDefault: false); // Optional; omit for active-only retrieval.

// Enable function invocation so the LLM can call the tools
IChatClient client = baseChatClient
    .AsBuilder()
    .UseFunctionInvocation()
    .Build();

var response = await client.GetResponseAsync(messages, options);
```

## See Also

* [Choose your integration](https://www.telerik.com/ai-observability-platform/documentation/agent-memory/choosing-your-integration)
* [Resolve Agent Memory issues](https://www.telerik.com/ai-observability-platform/documentation/troubleshooting#agent-memory)
