forked from themanojdesai/python-a2a
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathhttp.py
More file actions
1603 lines (1364 loc) · 66.9 KB
/
Copy pathhttp.py
File metadata and controls
1603 lines (1364 loc) · 66.9 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
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
"""
HTTP client for interacting with A2A-compatible agents.
"""
import requests
import uuid
import json
import re
import asyncio
import logging
from typing import Optional, Dict, Any, List, Union, AsyncGenerator, Callable
from ..models.message import Message, MessageRole
from ..models.conversation import Conversation
from ..models.content import (
TextContent, ErrorContent, FunctionCallContent,
FunctionResponseContent, FunctionParameter
)
from ..models.agent import AgentCard, AgentSkill
from ..models.task import Task, TaskStatus, TaskState
from .base import BaseA2AClient
from ..exceptions import A2AConnectionError, A2AResponseError, A2AStreamingError
logger = logging.getLogger(__name__)
class A2AClient(BaseA2AClient):
"""Client for interacting with HTTP-based A2A-compatible agents"""
def __init__(self, endpoint_url: str, headers: Optional[Dict[str, str]] = None,
timeout: int = 30, google_a2a_compatible: bool = False):
"""
Initialize a client with an agent endpoint URL
Args:
endpoint_url: The URL of the A2A-compatible agent
headers: Optional HTTP headers to include in requests
timeout: Request timeout in seconds
google_a2a_compatible: Whether to use Google A2A format by default (not normally needed)
"""
self.endpoint_url = endpoint_url.rstrip("/")
self.headers = headers or {}
self.timeout = timeout
self._use_google_a2a = google_a2a_compatible
self._protocol_detected = False # True after we've detected the protocol type
# Always include content type for JSON
if "Content-Type" not in self.headers:
self.headers["Content-Type"] = "application/json"
# Try to fetch the agent card for A2A protocol support
try:
self.agent_card = self._fetch_agent_card()
# Check for protocol hints in the agent card
if hasattr(self.agent_card, 'capabilities'):
capabilities = getattr(self.agent_card, 'capabilities', {})
if isinstance(capabilities, dict) and (
capabilities.get("google_a2a_compatible") or
capabilities.get("parts_array_format")
):
self._use_google_a2a = True
self._protocol_detected = True
except Exception as e:
# Create a default agent card
self.agent_card = AgentCard(
name="Unknown Agent",
description="Agent card not available",
url=self.endpoint_url,
version="unknown"
)
def _extract_json_from_html(self, html_content: str) -> Dict[str, Any]:
"""Extract JSON data from HTML content, typically when agent card is rendered as HTML"""
try:
# Look for JSON content in a <pre><code class="language-json"> block
# This pattern matches JSON content between code tags
json_pattern = re.compile(r'<code[^>]*>(.*?)</code>', re.DOTALL)
matches = json_pattern.findall(html_content)
if matches:
# Get the longest match (most likely to be complete JSON)
json_text = max(matches, key=len)
# Unescape HTML entities if present
json_text = json_text.replace('"', '"')
json_text = json_text.replace('"', '"')
json_text = json_text.replace('&', '&')
# Parse the extracted JSON
return json.loads(json_text)
except (json.JSONDecodeError, Exception):
pass
# Fallback: Try to find any JSON-like content in the HTML
try:
json_pattern = re.compile(r'({[\s\S]*"name"[\s\S]*})')
matches = json_pattern.findall(html_content)
if matches:
for match in matches:
try:
return json.loads(match)
except:
continue
except Exception:
pass
# No valid JSON found
return {}
def _fetch_agent_card(self):
"""Fetch the agent card from the well-known URL"""
# Try standard A2A endpoint first
try:
card_url = f"{self.endpoint_url}/agent.json"
# Add Accept header to prefer JSON
headers = dict(self.headers)
headers["Accept"] = "application/json"
# Make the request
response = requests.get(card_url, headers=headers, timeout=self.timeout)
response.raise_for_status()
# Check content type to handle HTML responses
content_type = response.headers.get("Content-Type", "").lower()
if "json" in content_type:
# JSON response
card_data = response.json()
elif "html" in content_type:
# HTML response - extract JSON
card_data = self._extract_json_from_html(response.text)
if not card_data:
raise ValueError("Could not extract JSON from HTML response")
else:
# Try parsing as JSON anyway
try:
card_data = response.json()
except json.JSONDecodeError:
# Try to extract JSON from the response text
card_data = self._extract_json_from_html(response.text)
if not card_data:
raise ValueError(f"Unexpected content type: {content_type}")
except Exception:
# Try alternate endpoint
try:
card_url = f"{self.endpoint_url}/a2a/agent.json"
# Add Accept header to prefer JSON
headers = dict(self.headers)
headers["Accept"] = "application/json"
# Make the request
response = requests.get(card_url, headers=headers, timeout=self.timeout)
response.raise_for_status()
# Check content type to handle HTML responses
content_type = response.headers.get("Content-Type", "").lower()
if "json" in content_type:
# JSON response
card_data = response.json()
elif "html" in content_type:
# HTML response - extract JSON
card_data = self._extract_json_from_html(response.text)
if not card_data:
raise ValueError("Could not extract JSON from HTML response")
else:
# Try parsing as JSON anyway
try:
card_data = response.json()
except json.JSONDecodeError:
# Try to extract JSON from the response text
card_data = self._extract_json_from_html(response.text)
if not card_data:
raise ValueError(f"Unexpected content type: {content_type}")
except Exception as e:
# If both fail, create a minimal card and continue
raise A2AConnectionError(
f"Failed to fetch agent card: {str(e)}"
) from e
# Check for protocol hints in the agent card
if "capabilities" in card_data:
capabilities = card_data.get("capabilities", {})
if isinstance(capabilities, dict) and (
capabilities.get("google_a2a_compatible") or
capabilities.get("parts_array_format")
):
self._use_google_a2a = True
self._protocol_detected = True
# Create AgentSkill objects from data
skills = []
for skill_data in card_data.get("skills", []):
skills.append(AgentSkill(
id=skill_data.get("id", str(uuid.uuid4())),
name=skill_data.get("name", "Unknown Skill"),
description=skill_data.get("description", ""),
tags=skill_data.get("tags", []),
examples=skill_data.get("examples", [])
))
# Create AgentCard object
return AgentCard(
name=card_data.get("name", "Unknown Agent"),
description=card_data.get("description", ""),
url=self.endpoint_url,
version=card_data.get("version", "unknown"),
authentication=card_data.get("authentication"),
capabilities=card_data.get("capabilities", {}),
skills=skills,
provider=card_data.get("provider"),
documentation_url=card_data.get("documentationUrl")
)
def _detect_protocol_version(self, response_error=None):
"""
Detect protocol version based on the error or endpoint probing
Args:
response_error: Optional error from a failed request
Returns:
True if Google A2A format should be used, False otherwise
"""
# Already detected or explicitly set
if self._protocol_detected:
return self._use_google_a2a
# Check if error contains clues about missing 'parts' field (Google A2A)
if response_error:
error_str = str(response_error).lower()
# Be very specific with error detection to avoid false positives
if "parts" in error_str and any(term in error_str for term in
["required", "missing", "validation", "schema"]):
self._use_google_a2a = True
self._protocol_detected = True
return True
# Special handling for specific common Google A2A errors with strict pattern
if ("tagged-union" in error_str and "parts" in error_str and
"missing" in error_str):
self._use_google_a2a = True
self._protocol_detected = True
return True
# No clear indication, use the current setting
return self._use_google_a2a
def send_message(self, message: Message) -> Message:
"""
Send a message to an A2A-compatible agent and get a response
Args:
message: The A2A message to send
Returns:
The agent's response as an A2A message
Raises:
A2AConnectionError: If connection to the agent fails
A2AResponseError: If the agent returns an invalid response
"""
# Try possible endpoints in order of preference
endpoints_to_try = [
self.endpoint_url, # Try the exact URL first
self.endpoint_url.rstrip("/"), # URL without trailing slash
f"{self.endpoint_url.rstrip('/')}/a2a", # Try /a2a endpoint
f"{self.endpoint_url.rstrip('/')}/tasks/send" # Try direct tasks endpoint
]
# Deduplicate endpoints
endpoints_to_try = list(dict.fromkeys(endpoints_to_try))
# First try A2A protocol style with tasks
task_response = None
for endpoint in endpoints_to_try:
try:
# Create a task from the message
task = self._create_task(message)
# Try to send the task to this endpoint
result = self._send_task(task, endpoint_override=endpoint)
# If we get here, the endpoint worked
# Remember this working endpoint for future requests
self.endpoint_url = endpoint
# Convert the task result back to a message
if result.artifacts and len(result.artifacts) > 0:
for artifact in result.artifacts:
if "parts" in artifact:
parts = artifact["parts"]
for part in parts:
if part.get("type") == "text":
task_response = Message(
content=TextContent(text=part.get("text", "")),
role=MessageRole.AGENT,
parent_message_id=message.message_id,
conversation_id=message.conversation_id
)
break
elif part.get("type") == "function_response":
task_response = Message(
content=FunctionResponseContent(
name=part.get("name", ""),
response=part.get("response", {})
),
role=MessageRole.AGENT,
parent_message_id=message.message_id,
conversation_id=message.conversation_id
)
break
elif part.get("type") == "function_call":
# Convert parameters to FunctionParameter objects
params = []
for param in part.get("parameters", []):
params.append(FunctionParameter(
name=param.get("name", ""),
value=param.get("value", "")
))
task_response = Message(
content=FunctionCallContent(
name=part.get("name", ""),
parameters=params
),
role=MessageRole.AGENT,
parent_message_id=message.message_id,
conversation_id=message.conversation_id
)
break
elif part.get("type") == "error":
task_response = Message(
content=ErrorContent(message=part.get("message", "")),
role=MessageRole.AGENT,
parent_message_id=message.message_id,
conversation_id=message.conversation_id
)
break
# If we got a response, return it
if task_response is not None:
return task_response
except Exception as e:
# This endpoint didn't work, try the next one
continue
# If we get here, all task endpoints failed, try legacy behavior - direct message posting
# First try standard python_a2a format
if not self._use_google_a2a:
for endpoint in endpoints_to_try:
try:
# Standard python_a2a format
response = requests.post(
endpoint,
json=message.to_dict(),
headers=self.headers,
timeout=self.timeout
)
# If we succeed, remember this endpoint
self.endpoint_url = endpoint
# Check for HTTP error
try:
response.raise_for_status()
except requests.HTTPError as e:
# Try to extract error details for protocol detection
try:
error_data = response.json()
error_str = json.dumps(error_data)
except:
error_str = str(e)
# Update protocol detection based on error
should_retry_with_google = self._detect_protocol_version(error_str)
# If we detected Google A2A format, break to try Google format
if should_retry_with_google:
break
# Otherwise try next endpoint
continue
# Process successful response
try:
# Check if response has clear Google A2A format indicators
response_data = response.json()
# Check for clear Google A2A format markers
if ("parts" in response_data and isinstance(response_data.get("parts"), list) and
"role" in response_data and not "content" in response_data):
# Response is in Google A2A format
self._use_google_a2a = True
self._protocol_detected = True
return Message.from_google_a2a(response_data)
else:
# Standard format
return Message.from_dict(response_data)
except ValueError as e:
# Try to get plain text if JSON parsing fails
try:
text_content = response.text.strip()
if text_content:
return Message(
content=TextContent(text=text_content),
role=MessageRole.AGENT,
parent_message_id=message.message_id,
conversation_id=message.conversation_id
)
except:
pass
# Try next endpoint
continue
except requests.RequestException:
# Try next endpoint
continue
# Try with Google A2A format if needed
if self._use_google_a2a or self._protocol_detected:
for endpoint in endpoints_to_try:
try:
# Google A2A format
response = requests.post(
endpoint,
json=message.to_google_a2a(),
headers=self.headers,
timeout=self.timeout
)
# If we succeed, remember this endpoint
self.endpoint_url = endpoint
# Handle HTTP errors
try:
response.raise_for_status()
except requests.HTTPError:
# Try next endpoint
continue
# Process successful response
try:
response_data = response.json()
# Check for Google A2A format response
if ("parts" in response_data and
isinstance(response_data.get("parts"), list) and
"role" in response_data):
# Google A2A format response
self._use_google_a2a = True
self._protocol_detected = True
return Message.from_google_a2a(response_data)
else:
# Standard format response
return Message.from_dict(response_data)
except Exception:
# Try to handle plain text response
try:
text = response.text.strip()
if text:
return Message(
content=TextContent(text=text),
role=MessageRole.AGENT,
parent_message_id=message.message_id,
conversation_id=message.conversation_id
)
except:
pass
# Try next endpoint
continue
except requests.RequestException:
# Try next endpoint
continue
# If we get here, all endpoints failed
return Message(
content=ErrorContent(message=f"Failed to communicate with agent at {self.endpoint_url}. Tried multiple endpoint variations."),
role=MessageRole.AGENT,
parent_message_id=message.message_id,
conversation_id=message.conversation_id
)
def send_conversation(self, conversation: Conversation) -> Conversation:
"""
Send a full conversation to an A2A-compatible agent and get an updated conversation
Args:
conversation: The A2A conversation to send
Returns:
The updated conversation with the agent's response
Raises:
A2AConnectionError: If connection to the agent fails
A2AResponseError: If the agent returns an invalid response
"""
# Try possible endpoints in order of preference
endpoints_to_try = [
self.endpoint_url, # Try the exact URL first
self.endpoint_url.rstrip("/"), # URL without trailing slash
f"{self.endpoint_url.rstrip('/')}/a2a", # Try /a2a endpoint
]
# Deduplicate endpoints
endpoints_to_try = list(dict.fromkeys(endpoints_to_try))
# First try standard python_a2a format
if not self._use_google_a2a:
for endpoint in endpoints_to_try:
try:
response = requests.post(
endpoint,
json=conversation.to_dict(),
headers=self.headers,
timeout=self.timeout
)
# If we succeed, remember this endpoint
self.endpoint_url = endpoint
# Handle HTTP errors
try:
response.raise_for_status()
except requests.HTTPError as e:
# Try to extract error details for protocol detection
try:
error_data = response.json()
error_str = json.dumps(error_data)
except:
error_str = str(e)
# Update protocol detection based on error
should_retry_with_google = self._detect_protocol_version(error_str)
# If we detected Google A2A format, break to try Google format
if should_retry_with_google:
break
# Otherwise try next endpoint
continue
# Process successful response
try:
response_data = response.json()
# Check if the response is in Google A2A format
if "messages" in response_data and isinstance(response_data["messages"], list):
if (response_data["messages"] and
"parts" in response_data["messages"][0] and
isinstance(response_data["messages"][0].get("parts"), list)):
# Response is in Google A2A format
self._use_google_a2a = True
self._protocol_detected = True
return Conversation.from_google_a2a(response_data)
# Standard format
return Conversation.from_dict(response_data)
except Exception:
# Try to extract text content if JSON parsing fails
try:
text_content = response.text.strip()
if text_content:
# Create a new message with the response text
last_message = conversation.messages[-1] if conversation.messages else None
parent_id = last_message.message_id if last_message else None
# Add a response message to the conversation
conversation.create_text_message(
text=text_content,
role=MessageRole.AGENT,
parent_message_id=parent_id
)
return conversation
except:
pass
# Try next endpoint
continue
except requests.RequestException:
# Try next endpoint
continue
# Try with Google A2A format if needed
if self._use_google_a2a or self._protocol_detected:
for endpoint in endpoints_to_try:
try:
# Google A2A format
response = requests.post(
endpoint,
json=conversation.to_google_a2a(),
headers=self.headers,
timeout=self.timeout
)
# If we succeed, remember this endpoint
self.endpoint_url = endpoint
# Handle HTTP errors
try:
response.raise_for_status()
except requests.HTTPError:
# Try next endpoint
continue
# Process successful response
try:
response_data = response.json()
# Check if the response is in Google A2A format
if "messages" in response_data and isinstance(response_data["messages"], list):
if (response_data["messages"] and
"parts" in response_data["messages"][0] and
isinstance(response_data["messages"][0].get("parts"), list)):
# Response is in Google A2A format
self._use_google_a2a = True
self._protocol_detected = True
return Conversation.from_google_a2a(response_data)
# Standard format
return Conversation.from_dict(response_data)
except Exception:
# Try to extract text content if JSON parsing fails
try:
text_content = response.text.strip()
if text_content:
# Create a new message with the response text
last_message = conversation.messages[-1] if conversation.messages else None
parent_id = last_message.message_id if last_message else None
# Add a response message to the conversation
conversation.create_text_message(
text=text_content,
role=MessageRole.AGENT,
parent_message_id=parent_id
)
return conversation
except:
pass
# Try next endpoint
continue
except requests.RequestException:
# Try next endpoint
continue
# If we get here, all endpoints failed
# Create an error message and add it to the conversation
error_msg = f"Failed to communicate with agent at {self.endpoint_url}. Tried multiple endpoint variations."
conversation.create_error_message(error_msg)
return conversation
def ask(self, message_text):
"""
Simple helper for text-based queries
Args:
message_text: Text message to send
Returns:
Text response from the agent
"""
# Check if message is already a Message object
if isinstance(message_text, str):
message = Message(
content=TextContent(text=message_text),
role=MessageRole.USER
)
else:
message = message_text
# Send message
response = self.send_message(message)
# Extract text from response
if response and hasattr(response, "content"):
content_type = getattr(response.content, "type", None)
if content_type == "text":
return response.content.text
elif content_type == "error":
return f"Error: {response.content.message}"
elif content_type == "function_response":
return f"Function '{response.content.name}' returned: {json.dumps(response.content.response, indent=2)}"
elif content_type == "function_call":
params = {p.name: p.value for p in response.content.parameters}
return f"Function call '{response.content.name}' with parameters: {json.dumps(params, indent=2)}"
elif response.content is not None:
return str(response.content)
# If text extraction from standard format failed, check for Google A2A format
if response:
try:
# Try to access parts directly
google_format = response.to_google_a2a()
if "parts" in google_format:
for part in google_format["parts"]:
if part.get("type") == "text" and "text" in part:
return part["text"]
except:
pass
return "No text response"
def _create_task(self, message):
"""
Create a new task with a message
Args:
message: Message object or text
Returns:
A new Task object
"""
# Convert string to Message if needed
if isinstance(message, str):
message = Message(
content=TextContent(text=message),
role=MessageRole.USER
)
# Create a task
return Task(
id=str(uuid.uuid4()),
message=message.to_dict() if isinstance(message, Message) else message
)
def _send_task(self, task, endpoint_override=None):
"""
Send a task to the agent
Args:
task: The task to send
endpoint_override: Optional override for the endpoint URL
Returns:
The updated task with the agent's response
"""
# Use the override if provided, otherwise use the standard endpoint
base_url = endpoint_override if endpoint_override else self.endpoint_url
# Prepare JSON-RPC request
request_data = {
"jsonrpc": "2.0",
"id": 1,
"method": "tasks/send",
"params": task.to_dict()
}
try:
# Try the standard endpoint first
endpoint_tried = False
try:
endpoint = f"{base_url}/tasks/send"
if endpoint.endswith("/tasks/send/tasks/send"):
# Avoid doubled path
endpoint = endpoint.replace("/tasks/send/tasks/send", "/tasks/send")
response = requests.post(
endpoint,
json=request_data,
headers=self.headers,
timeout=self.timeout
)
response.raise_for_status()
endpoint_tried = True
# Check for content type
if "application/json" not in response.headers.get("Content-Type", "").lower():
# Try to parse as JSON anyway
try:
response_data = response.json()
except json.JSONDecodeError:
# If we can't parse as JSON, consider this a failure
raise ValueError("Response is not valid JSON")
else:
response_data = response.json()
except Exception as e:
if endpoint_tried:
# If we've tried this endpoint and it failed with a response error,
# take a different approach for alternate endpoint
raise e
# Try the alternate endpoint
endpoint = f"{base_url}/a2a/tasks/send"
if endpoint.endswith("/a2a/tasks/send/a2a/tasks/send"):
# Avoid doubled path
endpoint = endpoint.replace("/a2a/tasks/send/a2a/tasks/send", "/a2a/tasks/send")
response = requests.post(
endpoint,
json=request_data,
headers=self.headers,
timeout=self.timeout
)
response.raise_for_status()
# Check for content type
if "application/json" not in response.headers.get("Content-Type", "").lower():
# Try to parse as JSON anyway
try:
response_data = response.json()
except json.JSONDecodeError:
# If we can't parse as JSON, consider this a failure
raise ValueError("Response is not valid JSON")
else:
response_data = response.json()
# Parse the response
result = response_data.get("result", {})
# If result is empty but we have a text response, create a task with it
if not result and isinstance(response_data, dict) and "text" in response_data:
# Create a simple task with text response
task.artifacts = [{
"parts": [{
"type": "text",
"text": response_data["text"]
}]
}]
task.status = TaskStatus(state=TaskState.COMPLETED)
return task
# Convert to Task object or use raw result if parsing fails
try:
result_task = Task.from_dict(result)
# Check if this might be Google A2A format
if result and isinstance(result, dict):
try:
for artifact in result.get("artifacts", []):
if "parts" in artifact and isinstance(artifact["parts"], list):
for part in artifact["parts"]:
if part.get("type") == "text" and "text" in part:
# This looks like Google A2A format
self._use_google_a2a = True
self._protocol_detected = True
break
except:
pass
return result_task
except Exception:
# Create a simple task with the raw result
task.artifacts = [{
"parts": [{
"type": "text",
"text": str(result)
}]
}]
task.status = TaskStatus(state=TaskState.COMPLETED)
return task
except Exception as e:
# Create an error task
task.status = TaskStatus(
state=TaskState.FAILED,
message={"error": str(e)}
)
return task
def get_task(self, task_id, history_length=0):
"""
Get a task by ID
Args:
task_id: ID of the task to retrieve
history_length: Number of history messages to include
Returns:
The task with current status and results
"""
# Prepare JSON-RPC request
request_data = {
"jsonrpc": "2.0",
"id": 1,
"method": "tasks/get",
"params": {
"id": task_id,
"historyLength": history_length
}
}
# Try possible endpoints
endpoints = [
f"{self.endpoint_url}/tasks/get",
f"{self.endpoint_url}/a2a/tasks/get"
]
for endpoint in endpoints:
try:
response = requests.post(
endpoint,
json=request_data,
headers=self.headers,
timeout=self.timeout
)
response.raise_for_status()
# Parse the response
response_data = response.json()
result = response_data.get("result", {})
# Try to convert to Task object
try:
# Check for Google A2A format
if result and isinstance(result, dict):
for artifact in result.get("artifacts", []):
if "parts" in artifact and isinstance(artifact["parts"], list):
for part in artifact["parts"]:
if part.get("type") == "text" and "text" in part:
# This looks like Google A2A format
self._use_google_a2a = True
self._protocol_detected = True
return Task.from_google_a2a(result)
# Standard format
return Task.from_dict(result)
except Exception:
# If conversion fails, create a simple task with the raw result
return Task(
id=task_id,
status=TaskStatus(state=TaskState.COMPLETED),
artifacts=[{
"parts": [{
"type": "text",
"text": str(result or response_data)
}]
}]
)
except Exception:
# Try next endpoint
continue
# If we get here, all endpoints failed
return Task(
id=task_id,
status=TaskStatus(
state=TaskState.FAILED,
message={"error": f"Failed to get task from {self.endpoint_url}"}
)
)
def cancel_task(self, task_id):
"""
Cancel a task
Args:
task_id: ID of the task to cancel
Returns:
The canceled task
"""
# Prepare JSON-RPC request
request_data = {
"jsonrpc": "2.0",
"id": 1,
"method": "tasks/cancel",
"params": {
"id": task_id
}
}
# Try possible endpoints
endpoints = [
f"{self.endpoint_url}/tasks/cancel",
f"{self.endpoint_url}/a2a/tasks/cancel"
]
for endpoint in endpoints:
try:
response = requests.post(
endpoint,
json=request_data,
headers=self.headers,
timeout=self.timeout
)
response.raise_for_status()
# Parse the response
response_data = response.json()
result = response_data.get("result", {})
# Try to convert to Task object
try:
# Check for Google A2A format
if result and isinstance(result, dict):
for artifact in result.get("artifacts", []):