forked from themanojdesai/python-a2a
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathconversation.py
More file actions
277 lines (229 loc) · 9.69 KB
/
Copy pathconversation.py
File metadata and controls
277 lines (229 loc) · 9.69 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
"""
Conversation models for the A2A protocol.
"""
import uuid
from dataclasses import dataclass, field
from typing import Dict, List, Optional, Any, ClassVar
from .base import BaseModel
from .message import Message, MessageRole
from .content import (
TextContent, FunctionCallContent, FunctionResponseContent,
ErrorContent, FunctionParameter
)
@dataclass
class Conversation(BaseModel):
"""Represents an A2A conversation"""
conversation_id: str = field(default_factory=lambda: str(uuid.uuid4()))
messages: List[Message] = field(default_factory=list)
metadata: Optional[Dict[str, Any]] = None
# Add a class variable to track protocol compatibility mode
_GOOGLE_A2A_COMPATIBILITY: ClassVar[bool] = False
def add_message(self, message: Message) -> Message:
"""
Add a message to the conversation
Args:
message: The message to add
Returns:
The added message
"""
# Set the conversation ID if not already set
if not message.conversation_id:
message.conversation_id = self.conversation_id
self.messages.append(message)
return message
def create_text_message(self, text: str, role: MessageRole,
parent_message_id: Optional[str] = None) -> Message:
"""
Create and add a text message to the conversation
Args:
text: The text content of the message
role: The role of the sender
parent_message_id: Optional ID of the parent message
Returns:
The created message
"""
content = TextContent(text=text)
message = Message(
content=content,
role=role,
conversation_id=self.conversation_id,
parent_message_id=parent_message_id
)
return self.add_message(message)
def create_function_call(self, name: str, parameters: List[Dict[str, Any]],
role: MessageRole = MessageRole.AGENT,
parent_message_id: Optional[str] = None) -> Message:
"""
Create and add a function call message to the conversation
Args:
name: The name of the function to call
parameters: List of parameter dictionaries with 'name' and 'value' keys
role: The role of the sender
parent_message_id: Optional ID of the parent message
Returns:
The created message
"""
function_params = [FunctionParameter(name=p["name"], value=p["value"]) for p in parameters]
content = FunctionCallContent(name=name, parameters=function_params)
message = Message(
content=content,
role=role,
conversation_id=self.conversation_id,
parent_message_id=parent_message_id
)
return self.add_message(message)
def create_function_response(self, name: str, response: Any,
role: MessageRole = MessageRole.AGENT,
parent_message_id: Optional[str] = None) -> Message:
"""
Create and add a function response message to the conversation
Args:
name: The name of the function that was called
response: The response data
role: The role of the sender
parent_message_id: Optional ID of the parent message
Returns:
The created message
"""
content = FunctionResponseContent(name=name, response=response)
message = Message(
content=content,
role=role,
conversation_id=self.conversation_id,
parent_message_id=parent_message_id
)
return self.add_message(message)
def create_error_message(self, error_message: str,
role: MessageRole = MessageRole.SYSTEM,
parent_message_id: Optional[str] = None) -> Message:
"""
Create and add an error message to the conversation
Args:
error_message: The error message text
role: The role of the sender
parent_message_id: Optional ID of the parent message
Returns:
The created message
"""
content = ErrorContent(message=error_message)
message = Message(
content=content,
role=role,
conversation_id=self.conversation_id,
parent_message_id=parent_message_id
)
return self.add_message(message)
@classmethod
def from_dict(cls, data: Dict[str, Any]) -> 'Conversation':
"""Create a Conversation from a dictionary"""
# Check if this is Google A2A format with careful detection
if ("messages" in data and isinstance(data.get("messages"), list) and
data["messages"] and "parts" in data["messages"][0] and
isinstance(data["messages"][0].get("parts"), list) and
"role" in data["messages"][0] and not "content" in data["messages"][0]):
return cls.from_google_a2a(data)
# Standard python_a2a format
messages = [Message.from_dict(m) for m in data.get("messages", [])]
return cls(
conversation_id=data.get("conversation_id", str(uuid.uuid4())),
messages=messages,
metadata=data.get("metadata")
)
def to_dict(self) -> Dict[str, Any]:
"""Convert Conversation to dictionary representation"""
# Use google format if compatibility mode is enabled
if self._GOOGLE_A2A_COMPATIBILITY:
return self.to_google_a2a()
# Standard python_a2a format
result = {
"conversation_id": self.conversation_id,
"messages": [message.to_dict() for message in self.messages]
}
if self.metadata:
result["metadata"] = self.metadata
return result
@classmethod
def from_google_a2a(cls, data: Dict[str, Any]) -> 'Conversation':
"""Create a Conversation from a Google A2A format dictionary
Args:
data: A dictionary in Google A2A format
Returns:
A Conversation object
"""
if not ("messages" in data and isinstance(data.get("messages"), list)):
raise ValueError("Not a valid Google A2A format conversation")
conversation_id = data.get("conversation_id", str(uuid.uuid4()))
# Process messages
messages = []
for msg_data in data.get("messages", []):
# Skip invalid messages
if not isinstance(msg_data, dict):
continue
# Try to convert from Google A2A format
if "parts" in msg_data and "role" in msg_data and not "content" in msg_data:
try:
# Convert message from Google A2A format
message = Message.from_google_a2a(msg_data)
# Set conversation_id if not already set
if not message.conversation_id:
message.conversation_id = conversation_id
messages.append(message)
except Exception:
# If conversion fails, skip this message
continue
else:
# Try standard format as fallback
try:
message = Message.from_dict(msg_data)
# Set conversation_id if not already set
if not message.conversation_id:
message.conversation_id = conversation_id
messages.append(message)
except Exception:
# If parsing fails, skip this message
continue
return cls(
conversation_id=conversation_id,
messages=messages,
metadata=data.get("metadata")
)
def to_google_a2a(self) -> Dict[str, Any]:
"""Convert to Google A2A format dictionary
Returns:
A dictionary in Google A2A format
"""
# Convert messages to Google A2A format
google_messages = []
for message in self.messages:
# Convert message to Google A2A format
try:
google_messages.append(message.to_google_a2a())
except Exception:
# Skip any messages that can't be converted
continue
# Create the Google A2A conversation dict
result = {
"conversation_id": self.conversation_id,
"messages": google_messages
}
if self.metadata:
result["metadata"] = self.metadata
return result
@classmethod
def enable_google_a2a_compatibility(cls, enable: bool = True) -> None:
"""Enable or disable Google A2A compatibility mode
When enabled, to_dict() will output Google A2A format
Args:
enable: Whether to enable compatibility mode
"""
cls._GOOGLE_A2A_COMPATIBILITY = enable
# Also update Message class compatibility
from .message import Message
Message.enable_google_a2a_compatibility(enable)
@classmethod
def is_google_a2a_compatibility_enabled(cls) -> bool:
"""Check if Google A2A compatibility mode is enabled
Returns:
True if enabled, False otherwise
"""
return cls._GOOGLE_A2A_COMPATIBILITY