Skip to content

The fastest, litest AI Gateway. Rust core with Python SDK. Call 100+ LLM APIs in OpenAI (or native) format with cost tracking, guardrails, load balancing, and logging [Bedrock, Azure, OpenAI, Anthropic, OpenAI, VertexAI, vLLM, Nvidia NIM]

[Feat] A2a Gateway - allow using bedrock agentcore, langgraph agents with A2a Gateway (#17786)

Ishaan Jaff7ad2a58dcd5e
diff --git a/litellm/a2a_protocol/litellm_completion_bridge/README.md b/litellm/a2a_protocol/litellm_completion_bridge/README.md
new file mode 100644
index 00000000000..a809e9bf55e
--- /dev/null
+++ b/litellm/a2a_protocol/litellm_completion_bridge/README.md
@@ -0,0 +1,74 @@
+# A2A to LiteLLM Completion Bridge
+
+Routes A2A protocol requests through `litellm.acompletion`, enabling any LiteLLM-supported provider to be invoked via A2A.
+
+## Flow
+
+```
+A2A Request → Transform → litellm.acompletion → Transform → A2A Response
+```
+
+## SDK Usage
+
+Use the existing `asend_message` and `asend_message_streaming` functions with `litellm_params`:
+
+```python
+from litellm.a2a_protocol import asend_message, asend_message_streaming
+from a2a.types import SendMessageRequest, SendStreamingMessageRequest, MessageSendParams
+from uuid import uuid4
+
+# Non-streaming
+request = SendMessageRequest(
+ id=str(uuid4()),
+ params=MessageSendParams(
+ message={"role": "user", "parts": [{"kind": "text", "text": "Hello!"}], "messageId": uuid4().hex}
+ )
+)
+response = await asend_message(
+ request=request,
+ api_base="http://localhost:2024",
+ litellm_params={"custom_llm_provider": "langgraph", "model": "agent"},
+)
+
+# Streaming
+stream_request = SendStreamingMessageRequest(
+ id=str(uuid4()),
+ params=MessageSendParams(
+ message={"role": "user", "parts": [{"kind": "text", "text": "Hello!"}], "messageId": uuid4().hex}
+ )
+)
+async for chunk in asend_message_streaming(
+ request=stream_request,
+ api_base="http://localhost:2024",
+ litellm_params={"custom_llm_provider": "langgraph", "model": "agent"},
+):
+ print(chunk)
+```
+
+## Proxy Usage
+
+Configure an agent with `custom_llm_provider` in `litellm_params`:
+
+```yaml
+agents:
+ - agent_name: my-langgraph-agent
+ agent_card_params:
+ name: "LangGraph Agent"
+ url: "http://localhost:2024" # Used as api_base
+ litellm_params:
+ custom_llm_provider: langgraph
+ model: agent
+```
+
+When an A2A request hits `/a2a/{agent_id}/message/send`, the bridge:
+
+1. Detects `custom_llm_provider` in agent's `litellm_params`
+2. Transforms A2A message → OpenAI messages
+3. Calls `litellm.acompletion(model="langgraph/agent", api_base="http://localhost:2024")`
+4. Transforms response → A2A format
+
+## Classes
+
+- `A2ACompletionBridgeTransformation` - Static methods for message format conversion
+- `A2ACompletionBridgeHandler` - Static methods for handling requests (streaming/non-streaming)
+
diff --git a/litellm/a2a_protocol/litellm_completion_bridge/__init__.py b/litellm/a2a_protocol/litellm_completion_bridge/__init__.py
new file mode 100644
index 00000000000..6c9df0ee285
--- /dev/null
+++ b/litellm/a2a_protocol/litellm_completion_bridge/__init__.py
@@ -0,0 +1,23 @@
+"""
+A2A to LiteLLM Completion Bridge.
+
+This module provides transformation between A2A protocol messages and
+LiteLLM completion API, enabling any LiteLLM-supported provider to be
+invoked via the A2A protocol.
+"""
+
+from litellm.a2a_protocol.litellm_completion_bridge.handler import (
+ A2ACompletionBridgeHandler,
+ handle_a2a_completion,
+ handle_a2a_completion_streaming,
+)
+from litellm.a2a_protocol.litellm_completion_bridge.transformation import (
+ A2ACompletionBridgeTransformation,
+)
+
+__all__ = [
+ "A2ACompletionBridgeTransformation",
+ "A2ACompletionBridgeHandler",
+ "handle_a2a_completion",
+ "handle_a2a_completion_streaming",
+]
diff --git a/litellm/a2a_protocol/litellm_completion_bridge/handler.py b/litellm/a2a_protocol/litellm_completion_bridge/handler.py
new file mode 100644
index 00000000000..e46d3580e60
--- /dev/null
+++ b/litellm/a2a_protocol/litellm_completion_bridge/handler.py
@@ -0,0 +1,185 @@
+"""
+Handler for A2A to LiteLLM completion bridge.
+
+Routes A2A requests through litellm.acompletion based on custom_llm_provider.
+"""
+
+from typing import Any, AsyncIterator, Dict, Optional
+
+import litellm
+from litellm._logging import verbose_logger
+from litellm.a2a_protocol.litellm_completion_bridge.transformation import (
+ A2ACompletionBridgeTransformation,
+)
+
+
+class A2ACompletionBridgeHandler:
+ """
+ Static methods for handling A2A requests via LiteLLM completion.
+ """
+
+ @staticmethod
+ async def handle_non_streaming(
+ request_id: str,
+ params: Dict[str, Any],
+ litellm_params: Dict[str, Any],
+ api_base: Optional[str] = None,
+ ) -> Dict[str, Any]:
+ """
+ Handle non-streaming A2A request via litellm.acompletion.
+
+ Args:
+ request_id: A2A JSON-RPC request ID
+ params: A2A MessageSendParams containing the message
+ litellm_params: Agent's litellm_params (custom_llm_provider, model, etc.)
+ api_base: API base URL from agent_card_params
+
+ Returns:
+ A2A SendMessageResponse dict
+ """
+ # Extract message from params
+ message = params.get("message", {})
+
+ # Transform A2A message to OpenAI format
+ openai_messages = A2ACompletionBridgeTransformation.a2a_message_to_openai_messages(
+ message
+ )
+
+ # Get completion params
+ custom_llm_provider = litellm_params.get("custom_llm_provider")
+ model = litellm_params.get("model", "agent")
+
+ # Build full model string if provider specified
+ if custom_llm_provider:
+ full_model = f"{custom_llm_provider}/{model}"
+ else:
+ full_model = model
+
+ verbose_logger.info(
+ f"A2A completion bridge: model={full_model}, api_base={api_base}"
+ )
+
+ # Call litellm.acompletion
+ response = await litellm.acompletion(
+ model=full_model,
+ messages=openai_messages,
+ api_base=api_base,
+ stream=False,
+ )
+
+ # Transform response to A2A format
+ a2a_response = A2ACompletionBridgeTransformation.openai_response_to_a2a_response(
+ response=response,
+ request_id=request_id,
+ )
+
+ verbose_logger.info(f"A2A completion bridge completed: request_id={request_id}")
+
+ return a2a_response
+
+ @staticmethod
+ async def handle_streaming(
+ request_id: str,
+ params: Dict[str, Any],
+ litellm_params: Dict[str, Any],
+ api_base: Optional[str] = None,
+ ) -> AsyncIterator[Dict[str, Any]]:
+ """
+ Handle streaming A2A request via litellm.acompletion with stream=True.
+
+ Args:
+ request_id: A2A JSON-RPC request ID
+ params: A2A MessageSendParams containing the message
+ litellm_params: Agent's litellm_params (custom_llm_provider, model, etc.)
+ api_base: API base URL from agent_card_params
+
+ Yields:
+ A2A streaming response chunks
+ """
+ # Extract message from params
+ message = params.get("message", {})
+
+ # Transform A2A message to OpenAI format
+ openai_messages = A2ACompletionBridgeTransformation.a2a_message_to_openai_messages(
+ message
+ )
+
+ # Get completion params
+ custom_llm_provider = litellm_params.get("custom_llm_provider")
+ model = litellm_params.get("model", "agent")
+
+ # Build full model string if provider specified
+ if custom_llm_provider:
+ full_model = f"{custom_llm_provider}/{model}"
+ else:
+ full_model = model
+
+ verbose_logger.info(
+ f"A2A completion bridge streaming: model={full_model}, api_base={api_base}"
+ )
+
+ # Call litellm.acompletion with streaming
+ response = await litellm.acompletion(
+ model=full_model,
+ messages=openai_messages,
+ api_base=api_base,
+ stream=True,
+ )
+
+ chunk_count = 0
+ async for chunk in response: # type: ignore[union-attr]
+ chunk_count += 1
+ a2a_chunk = A2ACompletionBridgeTransformation.openai_chunk_to_a2a_chunk(
+ chunk=chunk,
+ request_id=request_id,
+ is_final=False,
+ )
+ if a2a_chunk:
+ yield a2a_chunk
+
+ # Send final chunk
+ final_chunk = A2ACompletionBridgeTransformation.openai_chunk_to_a2a_chunk(
+ chunk=None,
+ request_id=request_id,
+ is_final=True,
+ )
+ if final_chunk:
+ # Clear content for final chunk
+ final_chunk["result"]["message"]["parts"][0]["text"] = ""
+ yield final_chunk
+
+ verbose_logger.info(
+ f"A2A completion bridge streaming completed: request_id={request_id}, chunks={chunk_count}"
+ )
+
+
+# Convenience functions that delegate to the class methods
+async def handle_a2a_completion(
+ request_id: str,
+ params: Dict[str, Any],
+ litellm_params: Dict[str, Any],
+ api_base: Optional[str] = None,
+) -> Dict[str, Any]:
+ """Convenience function for non-streaming A2A completion."""
+ return await A2ACompletionBridgeHandler.handle_non_streaming(
+ request_id=request_id,
+ params=params,
+ litellm_params=litellm_params,
+ api_base=api_base,
+ )
+
+
+async def handle_a2a_completion_streaming(
+ request_id: str,
+ params: Dict[str, Any],
+ litellm_params: Dict[str, Any],
+ api_base: Optional[str] = None,
+) -> AsyncIterator[Dict[str, Any]]:
+ """Convenience function for streaming A2A completion."""
+ async for chunk in A2ACompletionBridgeHandler.handle_streaming(
+ request_id=request_id,
+ params=params,
+ litellm_params=litellm_params,
+ api_base=api_base,
+ ):
+ yield chunk
diff --git a/litellm/a2a_protocol/litellm_completion_bridge/transformation.py b/litellm/a2a_protocol/litellm_completion_bridge/transformation.py
new file mode 100644
index 00000000000..0d37063d102
--- /dev/null
+++ b/litellm/a2a_protocol/litellm_completion_bridge/transformation.py
@@ -0,0 +1,152 @@
+"""
+Transformation utilities for A2A <-> OpenAI message format conversion.
+
+A2A Message Format:
+{
+ "role": "user",
+ "parts": [{"kind": "text", "text": "Hello!"}],
+ "messageId": "abc123"
+}
+
+OpenAI Message Format:
+{"role": "user", "content": "Hello!"}
+"""
+
+from typing import Any, Dict, List, Optional
+from uuid import uuid4
+
+from litellm._logging import verbose_logger
+
+
+class A2ACompletionBridgeTransformation:
+ """
+ Static methods for transforming between A2A and OpenAI message formats.
+ """
+
+ @staticmethod
+ def a2a_message_to_openai_messages(
+ a2a_message: Dict[str, Any],
+ ) -> List[Dict[str, str]]:
+ """
+ Transform an A2A message to OpenAI message format.
+
+ Args:
+ a2a_message: A2A message with role, parts, and messageId
+
+ Returns:
+ List of OpenAI-format messages
+ """
+ role = a2a_message.get("role", "user")
+ parts = a2a_message.get("parts", [])
+
+ # Map A2A roles to OpenAI roles
+ openai_role = role
+ if role == "user":
+ openai_role = "user"
+ elif role == "assistant":
+ openai_role = "assistant"
+ elif role == "system":
+ openai_role = "system"
+
+ # Extract text content from parts
+ content_parts = []
+ for part in parts:
+ kind = part.get("kind", "")
+ if kind == "text":
+ text = part.get("text", "")
+ content_parts.append(text)
+
+ content = "\n".join(content_parts) if content_parts else ""
+
+ verbose_logger.debug(
+ f"A2A -> OpenAI transform: role={role} -> {openai_role}, content_length={len(content)}"
+ )
+
+ return [{"role": openai_role, "content": content}]
+
+ @staticmethod
+ def openai_response_to_a2a_response(
+ response: Any,
+ request_id: Optional[str] = None,
+ ) -> Dict[str, Any]:
+ """
+ Transform a LiteLLM ModelResponse to A2A SendMessageResponse format.
+
+ Args:
+ response: LiteLLM ModelResponse object
+ request_id: Original A2A request ID
+
+ Returns:
+ A2A SendMessageResponse dict
+ """
+ # Extract content from response
+ content = ""
+ if hasattr(response, "choices") and response.choices:
+ choice = response.choices[0]
+ if hasattr(choice, "message") and choice.message:
+ content = choice.message.content or ""
+
+ # Build A2A message
+ a2a_message = {
+ "role": "agent",
+ "parts": [{"kind": "text", "text": content}],
+ "messageId": uuid4().hex,
+ }
+
+ # Build A2A response
+ a2a_response = {
+ "jsonrpc": "2.0",
+ "id": request_id,
+ "result": {
+ "message": a2a_message,
+ },
+ }
+
+ verbose_logger.debug(
+ f"OpenAI -> A2A transform: content_length={len(content)}"
+ )
+
+ return a2a_response
+
+ @staticmethod
+ def openai_chunk_to_a2a_chunk(
+ chunk: Any,
+ request_id: Optional[str] = None,
+ is_final: bool = False,
+ ) -> Optional[Dict[str, Any]]:
+ """
+ Transform a LiteLLM streaming chunk to A2A streaming format.
+
+ Args:
+ chunk: LiteLLM ModelResponse chunk
+ request_id: Original A2A request ID
+ is_final: Whether this is the final chunk
+
+ Returns:
+ A2A streaming chunk dict or None if no content
+ """
+ # Extract delta content
+ content = ""
+ if chunk is not None and hasattr(chunk, "choices") and chunk.choices:
+ choice = chunk.choices[0]
+ if hasattr(choice, "delta") and choice.delta:
+ content = choice.delta.content or ""
+
+ if not content and not is_final:
+ return None
+
+ # Build A2A streaming chunk
+ a2a_chunk = {
+ "jsonrpc": "2.0",
+ "id": request_id,
+ "result": {
+ "message": {
+ "role": "agent",
+ "parts": [{"kind": "text", "text": content}],
+ "messageId": uuid4().hex,
+ },
+ "final": is_final,
+ },
+ }
+
+ return a2a_chunk
diff --git a/litellm/a2a_protocol/main.py b/litellm/a2a_protocol/main.py
index 21b2ae81ad6..4d89dbb9454 100644
--- a/litellm/a2a_protocol/main.py
+++ b/litellm/a2a_protocol/main.py
@@ -97,46 +97,100 @@ def _get_a2a_model_info(a2a_client: Any, kwargs: Dict[str, Any]) -> str:
@client
async def asend_message(
- a2a_client: "A2AClientType",
- request: "SendMessageRequest",
+ a2a_client: Optional["A2AClientType"] = None,
+ request: Optional["SendMessageRequest"] = None,
+ api_base: Optional[str] = None,
+ litellm_params: Optional[Dict[str, Any]] = None,
**kwargs: Any,
) -> LiteLLMSendMessageResponse:
"""
Async: Send a message to an A2A agent.
Uses the @client decorator for LiteLLM logging and tracking.
+ If litellm_params contains custom_llm_provider, routes through the completion bridge.
Args:
- a2a_client: An initialized a2a.client.A2AClient instance
- request: SendMessageRequest from a2a.types
+ a2a_client: An initialized a2a.client.A2AClient instance (optional if using completion bridge)
+ request: SendMessageRequest from a2a.types (optional if using completion bridge with api_base)
+ api_base: API base URL (required for completion bridge, optional for standard A2A)
+ litellm_params: Optional dict with custom_llm_provider, model, etc. for completion bridge
**kwargs: Additional arguments passed to the client decorator
Returns:
LiteLLMSendMessageResponse (wraps a2a SendMessageResponse with _hidden_params)
- Example:
+ Example (standard A2A):
```python
from litellm.a2a_protocol import asend_message, create_a2a_client
from a2a.types import SendMessageRequest, MessageSendParams
from uuid import uuid4
- # Create client once
a2a_client = await create_a2a_client(base_url="http://localhost:10001")
-
- # Use it for multiple requests
request = SendMessageRequest(
id=str(uuid4()),
params=MessageSendParams(
- message={
- "role": "user",
- "parts": [{"kind": "text", "text": "Hello!"}],
- "messageId": uuid4().hex,
- }
+ message={"role": "user", "parts": [{"kind": "text", "text": "Hello!"}], "messageId": uuid4().hex}
)
)
response = await asend_message(a2a_client=a2a_client, request=request)
```
+
+ Example (completion bridge with LangGraph):
+ ```python
+ from litellm.a2a_protocol import asend_message
+ from a2a.types import SendMessageRequest, MessageSendParams
+ from uuid import uuid4
+
+ request = SendMessageRequest(
+ id=str(uuid4()),
+ params=MessageSendParams(
+ message={"role": "user", "parts": [{"kind": "text", "text": "Hello!"}], "messageId": uuid4().hex}
+ )
+ )
+ response = await asend_message(
+ request=request,
+ api_base="http://localhost:2024",
+ litellm_params={"custom_llm_provider": "langgraph", "model": "agent"},
+ )
+ ```
"""
+ litellm_params = litellm_params or {}
+ custom_llm_provider = litellm_params.get("custom_llm_provider")
+
+ # Route through completion bridge if custom_llm_provider is set
+ if custom_llm_provider:
+ if request is None:
+ raise ValueError("request is required for completion bridge")
+ if api_base is None:
+ raise ValueError("api_base is required for completion bridge")
+
+ verbose_logger.info(
+ f"A2A using completion bridge: provider={custom_llm_provider}, api_base={api_base}"
+ )
+
+ from litellm.a2a_protocol.litellm_completion_bridge.handler import (
+ A2ACompletionBridgeHandler,
+ )
+
+ # Extract params from request
+ params = request.params.model_dump(mode="json") if hasattr(request.params, "model_dump") else dict(request.params)
+
+ response_dict = await A2ACompletionBridgeHandler.handle_non_streaming(
+ request_id=str(request.id),
+ params=params,
+ litellm_params=litellm_params,
+ api_base=api_base,
+ )
+
+ # Convert to LiteLLMSendMessageResponse
+ return LiteLLMSendMessageResponse.from_dict(response_dict)
+
+ # Standard A2A client flow
+ if a2a_client is None:
+ raise ValueError("a2a_client is required for standard A2A flow")
+ if request is None:
+ raise ValueError("request is required")
+
agent_name = _get_a2a_model_info(a2a_client, kwargs)
verbose_logger.info(f"A2A send_message request_id={request.id}, agent={agent_name}")
@@ -196,19 +250,81 @@ def send_message(
async def asend_message_streaming(
- a2a_client: "A2AClientType",
- request: "SendStreamingMessageRequest",
-) -> AsyncIterator["SendStreamingMessageResponse"]:
+ a2a_client: Optional["A2AClientType"] = None,
+ request: Optional["SendStreamingMessageRequest"] = None,
+ api_base: Optional[str] = None,
+ litellm_params: Optional[Dict[str, Any]] = None,
+) -> AsyncIterator[Any]:
"""
Async: Send a streaming message to an A2A agent.
+ If litellm_params contains custom_llm_provider, routes through the completion bridge.
+
Args:
- a2a_client: An initialized a2a.client.A2AClient instance
+ a2a_client: An initialized a2a.client.A2AClient instance (optional if using completion bridge)
request: SendStreamingMessageRequest from a2a.types
+ api_base: API base URL (required for completion bridge)
+ litellm_params: Optional dict with custom_llm_provider, model, etc. for completion bridge
Yields:
SendStreamingMessageResponse chunks from the agent
+
+ Example (completion bridge with LangGraph):
+ ```python
+ from litellm.a2a_protocol import asend_message_streaming
+ from a2a.types import SendStreamingMessageRequest, MessageSendParams
+ from uuid import uuid4
+
+ request = SendStreamingMessageRequest(
+ id=str(uuid4()),
+ params=MessageSendParams(
+ message={"role": "user", "parts": [{"kind": "text", "text": "Hello!"}], "messageId": uuid4().hex}
+ )
+ )
+ async for chunk in asend_message_streaming(
+ request=request,
+ api_base="http://localhost:2024",
+ litellm_params={"custom_llm_provider": "langgraph", "model": "agent"},
+ ):
+ print(chunk)
+ ```
"""
+ litellm_params = litellm_params or {}
+ custom_llm_provider = litellm_params.get("custom_llm_provider")
+
+ # Route through completion bridge if custom_llm_provider is set
+ if custom_llm_provider:
+ if request is None:
+ raise ValueError("request is required for completion bridge")
+ if api_base is None:
+ raise ValueError("api_base is required for completion bridge")
+
+ verbose_logger.info(
+ f"A2A streaming using completion bridge: provider={custom_llm_provider}"
+ )
+
+ from litellm.a2a_protocol.litellm_completion_bridge.handler import (
+ A2ACompletionBridgeHandler,
+ )
+
+ # Extract params from request
+ params = request.params.model_dump(mode="json") if hasattr(request.params, "model_dump") else dict(request.params)
+
+ async for chunk in A2ACompletionBridgeHandler.handle_streaming(
+ request_id=str(request.id),
+ params=params,
+ litellm_params=litellm_params,
+ api_base=api_base,
+ ):
+ yield chunk
+ return
+
+ # Standard A2A client flow
+ if a2a_client is None:
+ raise ValueError("a2a_client is required for standard A2A flow")
+ if request is None:
+ raise ValueError("request is required")
+
verbose_logger.info(f"A2A send_message_streaming request_id={request.id}")
stream = a2a_client.send_message_streaming(request)
@@ -335,3 +451,5 @@ async def aget_agent_card(
f"Fetched agent card: {agent_card.name if hasattr(agent_card, 'name') else 'unknown'}"
)
return agent_card
+
+
diff --git a/litellm/proxy/agent_endpoints/a2a_endpoints.py b/litellm/proxy/agent_endpoints/a2a_endpoints.py
index 03b81fd7f70..84bbbb5d8a5 100644
--- a/litellm/proxy/agent_endpoints/a2a_endpoints.py
+++ b/litellm/proxy/agent_endpoints/a2a_endpoints.py
@@ -46,22 +46,32 @@ def _get_agent(agent_id: str):
async def _handle_stream_message(
- a2a_client: Any,
+ api_base: str,
request_id: str,
params: dict,
+ litellm_params: Optional[dict] = None,
) -> StreamingResponse:
- """Handle message/stream method."""
+ """Handle message/stream method via SDK functions."""
from a2a.types import MessageSendParams, SendStreamingMessageRequest
- a2a_request = SendStreamingMessageRequest(
- id=request_id,
- params=MessageSendParams(**params),
- )
+ from litellm.a2a_protocol import asend_message_streaming
async def stream_response():
try:
- async for chunk in a2a_client.send_message_streaming(a2a_request):
- yield json.dumps(chunk.model_dump(mode="json", exclude_none=True)) + "\n"
+ a2a_request = SendStreamingMessageRequest(
+ id=request_id,
+ params=MessageSendParams(**params),
+ )
+ async for chunk in asend_message_streaming(
+ request=a2a_request,
+ api_base=api_base,
+ litellm_params=litellm_params,
+ ):
+ # Chunk may be dict or object depending on bridge vs standard path
+ if hasattr(chunk, "model_dump"):
+ yield json.dumps(chunk.model_dump(mode="json", exclude_none=True)) + "\n"
+ else:
+ yield json.dumps(chunk) + "\n"
except Exception as e:
verbose_proxy_logger.exception(f"Error streaming A2A response: {e}")
yield json.dumps({
@@ -153,7 +163,9 @@ async def invoke_agent_a2a(
- message/send: Send a message and get a response
- message/stream: Send a message and stream the response
"""
- from litellm.a2a_protocol import asend_message, create_a2a_client
+ from a2a.types import MessageSendParams, SendMessageRequest
+
+ from litellm.a2a_protocol import asend_message
from litellm.proxy.agent_endpoints.auth.agent_permission_handler import (
AgentRequestHandler,
)
@@ -200,6 +212,9 @@ async def invoke_agent_a2a(
verbose_proxy_logger.info(f"Proxying A2A request to agent '{agent_id}' at {agent_url}")
+ # Get litellm_params (may include custom_llm_provider for completion bridge)
+ litellm_params = agent.litellm_params or {}
+
# Set up data dict for litellm processing
body.update({
"model": f"a2a_agent/{agent_name}",
@@ -216,28 +231,28 @@ async def invoke_agent_a2a(
version=version,
)
- # Create A2A client
- a2a_client = await create_a2a_client(base_url=agent_url)
-
+ # Route through SDK functions
if method == "message/send":
- from a2a.types import MessageSendParams, SendMessageRequest
-
a2a_request = SendMessageRequest(
id=request_id,
params=MessageSendParams(**params),
)
-
- # Pass litellm data through kwargs for proper logging
response = await asend_message(
- a2a_client=a2a_client,
request=a2a_request,
+ api_base=agent_url,
+ litellm_params=litellm_params,
metadata=data.get("metadata", {}),
proxy_server_request=data.get("proxy_server_request"),
)
return JSONResponse(content=response.model_dump(mode="json", exclude_none=True))
elif method == "message/stream":
- return await _handle_stream_message(a2a_client, request_id, params)
+ return await _handle_stream_message(
+ api_base=agent_url,
+ request_id=request_id,
+ params=params,
+ litellm_params=litellm_params,
+ )
else:
return _jsonrpc_error(request_id, -32601, f"Method '{method}' not found")
diff --git a/litellm/types/agents.py b/litellm/types/agents.py
index 7d8251ebff8..f4e410a3e2d 100644
--- a/litellm/types/agents.py
+++ b/litellm/types/agents.py
@@ -246,3 +246,16 @@ class LiteLLMSendMessageResponse(LiteLLMPydanticObjectBase):
response_dict = response.model_dump(mode="json", exclude_none=True)
return cls(**response_dict)
+
+ @classmethod
+ def from_dict(cls, response_dict: Dict[str, Any]) -> "LiteLLMSendMessageResponse":
+ """
+ Create a LiteLLMSendMessageResponse from a dict.
+
+ Args:
+ response_dict: Dict with A2A response structure
+
+ Returns:
+ LiteLLMSendMessageResponse with _hidden_params support
+ """
+ return cls(**response_dict)
diff --git a/tests/agent_tests/test_a2a_completion_bridge.py b/tests/agent_tests/test_a2a_completion_bridge.py
new file mode 100644
index 00000000000..4f4959a7fb2
--- /dev/null
+++ b/tests/agent_tests/test_a2a_completion_bridge.py
@@ -0,0 +1,116 @@
+"""
+Test for A2A to LiteLLM Completion Bridge.
+
+Tests the SDK-level functions that route A2A requests through litellm.acompletion.
+
+Run with:
+ pytest tests/agent_tests/test_a2a_completion_bridge.py -v -s
+
+Prerequisites:
+ - LangGraph server running on localhost:2024
+"""
+
+import os
+import sys
+from uuid import uuid4
+
+import pytest
+
+sys.path.insert(0, os.path.abspath("../.."))
+
+import litellm
+from a2a.types import MessageSendParams, SendMessageRequest, SendStreamingMessageRequest
+
+
+async def test_a2a_completion_bridge_non_streaming():
+ """
+ Test non-streaming A2A request via the completion bridge with LangGraph provider.
+ """
+ from litellm.a2a_protocol import asend_message
+
+ litellm._turn_on_debug()
+
+ send_message_payload = {
+ "message": {
+ "role": "user",
+ "parts": [{"kind": "text", "text": "What is 2 + 2?"}],
+ "messageId": uuid4().hex,
+ }
+ }
+
+ request = SendMessageRequest(
+ id=str(uuid4()),
+ params=MessageSendParams(**send_message_payload), # type: ignore
+ )
+
+ response = await asend_message(
+ request=request,
+ api_base="http://localhost:2024",
+ litellm_params={"custom_llm_provider": "langgraph", "model": "agent"},
+ )
+
+ # Validate response is LiteLLMSendMessageResponse
+ assert response.jsonrpc == "2.0"
+ assert response.id is not None
+ assert response.result is not None
+ assert "message" in response.result
+
+ message = response.result["message"]
+ assert "role" in message
+ assert message["role"] == "agent"
+ assert "parts" in message
+ assert len(message["parts"]) > 0
+ assert message["parts"][0]["kind"] == "text"
+ assert len(message["parts"][0]["text"]) > 0
+
+ print(f"Response: {response.model_dump(mode='json', exclude_none=True)}")
+
+
+async def test_a2a_completion_bridge_streaming():
+ """
+ Test streaming A2A request via the completion bridge with LangGraph provider.
+ """
+ from litellm.a2a_protocol import asend_message_streaming
+
+ litellm._turn_on_debug()
+
+ send_message_payload = {
+ "message": {
+ "role": "user",
+ "parts": [{"kind": "text", "text": "Count from 1 to 5."}],
+ "messageId": uuid4().hex,
+ }
+ }
+
+ request = SendStreamingMessageRequest(
+ id=str(uuid4()),
+ params=MessageSendParams(**send_message_payload), # type: ignore
+ )
+
+ chunks = []
+ async for chunk in asend_message_streaming(
+ request=request,
+ api_base="http://localhost:2024",
+ litellm_params={"custom_llm_provider": "langgraph", "model": "agent"},
+ ):
+ chunks.append(chunk)
+ print(f"Chunk: {chunk}")
+
+ # Validate we received chunks
+ assert len(chunks) > 0
+
+ # Validate chunk structure (chunks are dicts from bridge)
+ for chunk in chunks:
+ assert "jsonrpc" in chunk
+ assert chunk["jsonrpc"] == "2.0"
+ assert "result" in chunk
+ assert "message" in chunk["result"]
+ message = chunk["result"]["message"]
+ assert "role" in message
+ assert message["role"] == "agent"
+ assert "parts" in message
+
+ print(f"Received {len(chunks)} chunks")
+