Skip to content

Commit de2f1bf

Browse files
authored
ADR Agents - AgentChat Serialization Design (#6972)
### Motivation and Context <!-- Thank you for your contribution to the semantic-kernel repo! Please help reviewers and future users, providing the following information: 1. Why is this change required? 2. What problem does it solve? 3. What scenario does it contribute to? 4. If it fixes an open issue, please link to the issue here. --> Users of the Agent Framework are unable to store and later retrieve conversation state when using an AgentChat to coordinate Agent interactions. This limits the ability for an agent conversation to single use as it must be maintained with memory of the process that initiated the conversation. Formalizing a mechanism that supports serialization and deserialization of any AgentChat class provides an avenue to capture and restore state across multiple sessions as well as compute boundaries. ### Description <!-- Describe your changes, the overall approach, the underlying design. These notes will help understanding how your code works. Thanks! --> Design in ADR form for input, exploration of alternatives, and review. ### Contribution Checklist <!-- Before submitting this PR, please make sure: --> - [X] The PR follows the [SK Contribution Guidelines](https://github.com/microsoft/semantic-kernel/blob/main/CONTRIBUTING.md) and the [pre-submission formatting script](https://github.com/microsoft/semantic-kernel/blob/main/CONTRIBUTING.md#development-scripts) raises no violations - [X] I didn't break anyone 😄
1 parent 7a06d80 commit de2f1bf

4 files changed

Lines changed: 405 additions & 0 deletions

File tree

Lines changed: 382 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,382 @@
1+
---
2+
status: proposed
3+
contact: crickman
4+
date: 2024-06-24
5+
deciders: bentho, matthewbolanos
6+
---
7+
8+
# `AgentChat` Serialization / Deserialization
9+
10+
## Context and Problem Statement
11+
Users of the _Agent Framework_ are unable to store and later retrieve conversation state when using an `AgentChat` to coordinate `Agent` interactions. This limits the ability for an agent conversation to single use as it must be maintained with memory of the process that initiated the conversation.
12+
13+
Formalizing a mechanism that supports serialization and deserialization of any `AgentChat` class provides an avenue to capture and restore state across multiple sessions as well as compute boundaries.
14+
15+
#### Goals
16+
- **Capture & Restore Primary Chat History**: The primary `AgentChat` history must be captured and restored for full fidelity.
17+
- **Capture & Restore Channel State**: In addition to the primary chat history, the state for each `AgentChannel` within the `AgentChat` must be captured and restored.
18+
- **Capture Agent Metadata**: Capturing the agent Identifier, Name, and Type upon serialization provides a guidance on how to restore the the `AgentChat` during deserialization.
19+
20+
21+
#### Non-Goals
22+
- **Manage agent definition:** An `Agent` definition shall not be captured as part of the conversation state. `Agent` instances will not be produced when deserializing the state of an `AgentChat` class.
23+
- **Manage secrets or api-keys:** Secrets / api-keys are required when producing an `Agent` instance. Managing this type of sensitive data is out-of-scope due to security considerations.
24+
25+
26+
## Issues
27+
28+
- Serialized `ChatHistory` must be equivalent across platforms / languages for interoperability
29+
30+
## Cases
31+
When restoring an `AgentChat`, the application must also re-create the `Agent` instances participating in the chat (outside of the control of the deserialization process). This creates the opportunity for the following cases:
32+
33+
#### 1. **Equivalent:** All of the original agent types (channels) available in the restored chat.
34+
This shall result in a full-fidelity restoration of of the original chat.
35+
36+
|Source Chat|Target Chat|
37+
|---|---|
38+
|`ChatCompletionAgent`|`ChatCompletionAgent`|
39+
|`OpenAIAssistantAgent`|`OpenAIAssistantAgent`|
40+
|`ChatCompletionAgent` & `OpenAIAssistantAgent`|`ChatCompletionAgent` & `OpenAIAssistantAgent`|
41+
42+
#### 2. **Enhanced:** Additional original agent types (channels) available in the restored chat.
43+
This shall also result in a full-fidelity restoration of of the original chat.
44+
Any new agent type (channel) will synchronize to the chat once restored (identical to adding a new agent type to a chat that is progress).
45+
46+
|Source Chat|Target Chat|
47+
|---|---|
48+
|`ChatCompletionAgent`|`ChatCompletionAgent` & `OpenAIAssistantAgent`|
49+
|`OpenAIAssistantAgent`|`ChatCompletionAgent` & `OpenAIAssistantAgent`|
50+
51+
#### 3. **Reduced:** A subset of original agent types (channels) available in the restored chat.
52+
This shall also result in a full-fidelity restoration of of the original chat to the available channels. Introduction of a missing agent type (channel) post restoration will
53+
synchronize the channel to the current chat (identical to adding a new agent type to a chat that is progress).
54+
55+
|Source Chat|Target Chat|
56+
|---|---|
57+
|`ChatCompletionAgent` & `OpenAIAssistantAgent`|`ChatCompletionAgent`|
58+
|`ChatCompletionAgent` & `OpenAIAssistantAgent`|`OpenAIAssistantAgent`|
59+
60+
#### 4. **Empty:** No agents available in the restored chat.
61+
This shall result in an immediate exception (fail-fast) in order to strongly indicate that
62+
the chat has not been restored. The chat may have agents added in order to attempt a successful restoration, or utilized on its own. That is, the `AgentChat` instance isn't invalidated.
63+
64+
#### 5. **Invalid:** Chat has already developed history or channels state.
65+
This shall result in an immediate exception (fail-fast) in order to strongly indicate that
66+
the chat has not been restored. The chat may continue to be utilized as the `AgentChat` instance isn't invalidated.
67+
68+
#### Notes:
69+
70+
> Once restored, additional `Agent` instances may join the `AgentChat`, no different from any `AgentChat` instance.
71+
72+
73+
## Analysis
74+
75+
#### Relationships:
76+
77+
The relationships between any `AgentChat`, the `Agent` instances participating in the conversation, and the associated `AgentChannel` conduits are illustrated in the following diagram:
78+
79+
<p align="center">
80+
<kbd><img src="diagrams/agentchat-relationships.png" style="width: 220pt;"></kbd>
81+
</p>
82+
83+
While an `AgentChat` manages a primary `ChatHistory`, each `AgentChannel` manages how that history is adapted to the specific `Agent` modality. For instance, an `AgentChannel` for an `Agent` based on the Open AI Assistant API tracks the associated _thread-id_. Whereas a `ChatCompletionAgent` manages an adapted `ChatHistory` instance of its own.
84+
85+
This implies that logically the `AgentChat` state must retain the primary `ChatHistory` in addition to the appropriate state for each `AgentChannel`:
86+
87+
88+
#### Logical State:
89+
90+
These relationships translate into the following logical state definition:
91+
92+
<p align="center">
93+
<kbd><img src="diagrams/agentchat-state.png" style="width: 220pt;"></kbd>
94+
</p>
95+
96+
97+
#### Serialized State:
98+
99+
```javascript
100+
{
101+
// Serialized ChatHistory
102+
"history": [
103+
{ "role": "user", "items": [ /* ... */ ] },
104+
{ "role": "assistant", "name": "John", "items": [ /* ... */ ] },
105+
// ...
106+
],
107+
// Serialized Participants
108+
"participants": [
109+
{
110+
"id": "01b6a120-7fef-45e2-aafb-81cf4a90d931",
111+
"name": "John",
112+
"type": "ChatCompletionAgent"
113+
},
114+
// ...
115+
],
116+
// Serialized AgentChannel state
117+
"channels": [
118+
{
119+
"channelkey": "Vdx37EnWT9BS+kkCkEgFCg9uHvHNw1+hXMA4sgNMKs4=",
120+
"channelstate": "...", // Serialized state for an AgentChannel
121+
},
122+
// ...
123+
]
124+
}
125+
```
126+
127+
128+
## Options
129+
130+
#### 1. JSON Serializer:
131+
132+
A dominant serialization pattern is to use the dotnet `JsonSerializer`. This is the approach relied upon by the _Semantic Kernel_ content types.
133+
134+
**Serialize Example:**
135+
136+
(_dotnet_)
137+
```c#
138+
// Create the agents
139+
ChatCompletionAgent agent1 = ...;
140+
OpenAIAssistantAgent agent2 = ...;
141+
142+
// Create the agent-chat
143+
AgentGroupChat chat = new(agent1, agent2);
144+
145+
// Serialize the chat object to JSON
146+
string chatState = JsonSerializer.Serialize(chat);
147+
```
148+
149+
(_python_)
150+
```python
151+
# Create the agents
152+
agent1 = ChatCompletionAgent(...)
153+
agent2 = OpenAIAssistantAgent(...)
154+
155+
# Create the agent-chat
156+
chat = AgentGroupChat(agent1, agent2)
157+
158+
# Serialize the chat to JSON
159+
chat_state = chat.model_dump()
160+
```
161+
162+
**Deserialize Example:**
163+
164+
(_dotnet_)
165+
```c#
166+
// Deserialize JSON
167+
AgentGroupChat chat = JsonSerializer.Deserialize<AgentGroupChat>(chatState);
168+
```
169+
170+
(_python_)
171+
```python
172+
# Deserialize JSON
173+
def agent_group_chat_decoder(obj) -> AgentGroupChat:
174+
pass
175+
176+
chat = json.loads(chat_state, object_hook=agent_group_chat_decoder)
177+
```
178+
179+
**Pro:**
180+
- Doesn't require knowledge of a serialization pattern specific to the _Agent Framework_.
181+
182+
**Con:**
183+
- Both `AgentChat` nor `AgentChannel` are designed as a service classes, not _data transfer objects_ (DTO's). Implies disruptive refactoring. (Think: complete re-write)
184+
- Requires caller to address complexity to support serialization of unknown `AgentChannel` and `AgentChat` subclasses.
185+
- Limits ability to post process when restoring chat (e.g. channel synchronization).
186+
- Absence of `Agent` instances in deserialization interferes with ability to restore any `AgentChannel`.
187+
188+
189+
#### 2. `AgentChat` Serializer:
190+
191+
Introducing a serializer with specific knowledge of `AgentChat` contracts enables the ability to streamline serialization and deserialization.
192+
193+
(_dotnet_)
194+
```c#
195+
class AgentChatSerializer
196+
{
197+
// Captures chat state to the provided stream
198+
static async Task SerializeAsync(AgentChat chat, Stream stream)
199+
200+
// Reads chat state from the provided stream and returns serializer
201+
static async Task<AgentChatSerializer> DeserializeAsync(AgentChat chat, Stream stream)
202+
203+
// Provides list of participants
204+
IReadOnlyList<ChatParticipant> GetParticipants();
205+
206+
// Restores the chat state
207+
Task RestoreAsync(AgentChat chat);
208+
}
209+
```
210+
211+
(_python_)
212+
```python
213+
class AgentChatSerializer:
214+
215+
# Captures chat state to the provided stream
216+
@staticmethod
217+
async def serialize(chat: AgentChat, stream);
218+
pass
219+
220+
# Reads chat state from the provided stream and returns serializer
221+
@staticmethod
222+
async def deserialize(chat: AgentChat, stream) -> AgentChatSerializer:
223+
pass
224+
225+
# Provides list of participants
226+
def get_participants(self) -> list[ChatParticipant]:
227+
pass
228+
229+
# Restores the chat state
230+
async def restore(self, chat: AgentChat):
231+
pass
232+
```
233+
234+
**Pro:**
235+
- Able to clearly define the chat-state, separate from the chat _service_ requirements.
236+
- Support any `AgentChat` and `AgentChannel` subclass.
237+
- Ability to support post processing when restoring chat (e.g. channel synchronization).
238+
- Allows any `AgentChat` to be properly initialized prior to deserialization.
239+
- Allows for inspection of `ChatParticipant` metadata.
240+
241+
**Con:**
242+
- Require knowledge of a serialization pattern specific to the _Agent Framework_.
243+
244+
**Serialize Example:**
245+
246+
(_dotnet_)
247+
```c#
248+
// Create agents
249+
ChatCompletionAgent agent1 = ...;
250+
OpenAIAssistantAgent agent2 = ...;
251+
252+
// Create agent-chat
253+
AgentGroupChat chat = new(agent1, agent2);
254+
255+
// Initiate conversation
256+
await chat.InvokeAsync();
257+
258+
// Initialize the serialization stream
259+
async using Stream stream = ...;
260+
261+
// Capture agent-chat
262+
await AgentChatSerializer.SerializeAsync(chat, stream);
263+
```
264+
265+
(_python_)
266+
```python
267+
# Create agents
268+
agent1 = ChatCompletionAgent(...)
269+
agent2 = OpenAIAssistantAgent(...)
270+
271+
# Create agent-chat
272+
chat = AgentGroupChat(agent1, agent2)
273+
274+
# Initiate conversation
275+
await chat.invoke()
276+
277+
# Initialize the serialization stream
278+
async with ... as stream:
279+
280+
# Capture agent-chat
281+
await AgentChatSerializer.serialize(chat, stream)
282+
```
283+
284+
**Deserialize Example:**
285+
286+
(_dotnet_)
287+
```c#
288+
// Create agents
289+
ChatCompletionAgent agent1 = ...;
290+
OpenAIAssistantAgent agent2 = ...;
291+
292+
Dictionary<string, Agent> agents =
293+
new()
294+
{
295+
{ agent1.Id, agent1 },
296+
{ agent2.Id, agent2 },
297+
}
298+
299+
// Initialize the deserialization stream
300+
async using Stream stream = ...;
301+
AgentChatSerializer serializer = AgentChatSerializer.Deserialize(stream);
302+
303+
// Create agent-chat
304+
AgentGroupChat chat = new();
305+
306+
// Restore agents
307+
foreach (ChatParticipant participant in serializer.GetParticipants())
308+
{
309+
chat.AddAgent(agents[participant.Id]);
310+
}
311+
312+
// Restore chat
313+
serializer.Deserialize(chat);
314+
315+
// Continue chat
316+
await chat.InvokeAsync();
317+
```
318+
319+
(_python_)
320+
```python
321+
# Create agents
322+
agent1 = ChatCompletionAgent(...)
323+
agent2 = OpenAIAssistantAgent(...)
324+
325+
agents = {
326+
agent1.id: agent1,
327+
agent2.id: agent2,
328+
}
329+
330+
# Initialize the serialization stream
331+
async with ... as stream:
332+
serializer = await AgentChatSerializer.serialize(stream)
333+
334+
# Create agent-chat
335+
chat = AgentGroupChat(agent1, agent2)
336+
337+
# Restore agents
338+
for participant in serializer.get_participants():
339+
chat.add_agent(agents[participant.id])
340+
341+
# Restore agent-chat
342+
await serializer.deserialize(chat)
343+
344+
# Continue chat
345+
await chat.invoke();
346+
```
347+
348+
#### 3. Encoded State
349+
350+
This option is identical to the second option; however, each discrete state is base64 encoded to discourage modification / manipulation of the captured state.
351+
352+
**Pro:**
353+
- Discourages ability to inspect and modify.
354+
355+
**Con:**
356+
- Obscures ability to inspect.
357+
- Still able to decode to inspect and modify.
358+
359+
**Serialized State:**
360+
```javascript
361+
{
362+
"history": "VGhpcyBpcyB0aGUgcHJpbWFyeSBjaGF0IGhpc3Rvcnkg...",
363+
"participants": [
364+
{
365+
"aId37EnWT9BS+kkCkEgFCg9uHvHNw1+hXMA4sgNMKs4...",
366+
// ...
367+
},
368+
],
369+
"channels": [
370+
{
371+
"channelkey": "Vdx37EnWT9BS+kkCkEgFCg9uHvHNw1+hXMA4sgNMKs4=",
372+
"channelstate": "VGhpcyBpcyBhZ2VudCBjaGFubmVsIHN0YXRlIGV4YW1wbG..."
373+
},
374+
// ...
375+
]
376+
}
377+
```
378+
379+
380+
## Outcome
381+
382+
TBD
52.2 KB
Loading

0 commit comments

Comments
 (0)