Best practice for handling per-user chat history with DI in agent-based REST APIs #4930
-
|
I’m working on an agent-based system where a REST endpoint invokes an AI agent, and subsequent requests for the same user need to be context-aware by leveraging stored conversation history. Current Design
Challenge
What I’m Trying to Understand
Take a loot at my redis history provider and factory class below RedisChatHistoryProvider.txt Additional Context (Current Invocation Pattern) From my REST endpoint, this is how I’m currently invoking the agent: |
Beta Was this translation helpful? Give feedback.
Replies: 1 comment
-
|
Great question — the design you've landed on is actually very close to the framework's intended pattern, but the framework has a first-class hook for exactly this scenario that lets you drop the factory altogether. Walking through your three questions: 1. The agent should be a singleton, not per-request
public static IHostedAgentBuilder AddAIAgent(
this IServiceCollection services,
string name,
string? instructions,
ServiceLifetime lifetime = ServiceLifetime.Singleton) { ... }So you don't need a factory keyed on 2. The conversation state belongs in an
|
| Your question | Recommended answer |
|---|---|
Is passing userId via a factory the right way? |
No — push that data into the conversation id the endpoint receives, and let DI hand you a singleton agent + a keyed AgentSessionStore. |
| Is stateless-agent + history-rehydration correct? | Yes, that's exactly the design. Just use AgentSessionStore instead of a custom ChatHistoryProvider as the rehydration boundary. |
| Should agents be long-lived per conversation? | No — agents are singletons. Sessions are the per-conversation thing, and they live in the store. |
Bonus: if you'd rather keep ChatHistoryProvider
There's also a separate ChatHistoryProvider extensibility point hung off ChatClientAgentOptions — useful if you want the agent itself to own message persistence (e.g. for server-side responses APIs). Microsoft.Agents.AI.CosmosNoSql ships WithCosmosDBChatHistoryProvider as a reference implementation — a RedisChatHistoryProvider would follow the same shape. But for the REST scenario you described, AgentSessionStore is the cleaner fit.
Beta Was this translation helpful? Give feedback.
Great question — the design you've landed on is actually very close to the framework's intended pattern, but the framework has a first-class hook for exactly this scenario that lets you drop the factory altogether. Walking through your three questions:
1. The agent should be a singleton, not per-request
AIAgentinstances are designed to be stateless and long-lived. All of theAddAIAgentoverloads inMicrosoft.Agents.AI.Hostingdefault toServiceLifetime.Singletonfor that reason — see AgentHostingServiceCollectionExtensions.cs: