We continue our journey through the Microsoft.Extensions.AI
library. Another basic feature that you certainly will need when building your own AI agents, is a way to keep track of your chat history. This is useful as it allows the LLM to build up a context based on the interactions that already took place.
This post is part of a blog series. Other posts so far:
- Part I – An introduction to Microsoft.Extensions.AI
- Part II – ASP.NET Core integration
- Part III –Tool calling
- Part IV – Telemetry integration
- Part V – Chat history (this post)
Chat history
The basics to maintaining a history is simple. You need to build up a list of previously exchanged chat messages:
Remark: Notice the different roles we can link to the message so the LLM knows who provided what information.
Once we have that list, we pass it along when calling the LLM instead of only our specific input:
The AI service can now use this information during our interactions:
Stateless vs stateful services
Although the approach above will certainly work, it becomes more expensive over time. More and more context needs to send and shared between the chat client and the LLM increasing token size and complexity.
Some of the available AI services are available as stateful services being able to track the previous interactions. When the AI service supports this model, you no longer need to send the full conversation with every request but only need to pass a conversation id.
Here is an example that works in both scenario’s: