python-a2a

repository·main·Indexed 21 days ago

https://github.com/themanojdesai/python-a2a

A comprehensive Python library for Google's Agent-to-Agent (A2A) protocol, version 0.5.10. It features integrated Model Context Protocol (MCP) support, LangChain integration, and Agent Flow—a visual workflow editor with a REST API for building interoperable multi-agent ecosystems. The library supports LLM integrations with OpenAI, Anthropic, and AWS Bedrock, and provides extensive capabilities for real-time streaming, agent discovery, and task-based orchestration.

Tokens
65.7K
Snippets
175
Records
215
Agent score
76%

What's inside python-a2a

  1. Overview of A2A streaming examples

    main

    The examples/streaming/ directory provides a progression of implementations for different streaming use cases:

    • basic_streaming.py: Minimal implementation of a streaming server and client with proper dictionary chunk handling.
    • 01_basic_streaming.py: Comprehensive introduction covering simulated thinking delays and natural language chunking.
    • 02_advanced_streaming.py: Focuses on metrics tracking, performance visualization, and various chunking strategies (sentence, word, paragraph).
    • 03_streaming_llm_integration.py: Demonstrates bridging LLM provider APIs (OpenAI, Anthropic, Bedrock) with A2A using transformer pipelines.
    • 04_task_based_streaming.py: Implements structured task state transitions (e.g., WAITING, COMPLETED) and artifact generation.
    • 05_streaming_ui_integration.py: Shows CLI-based visualization and Web interfaces using Server-Sent Events (SSE) with interactive controls (pause, resume, cancel).
    • 06_distributed_streaming.py: Demonstrates distributed architecture with multiple servers, load balancing, and stream aggregation.
  2. What is Python A2A?

    main

    Python A2A is a production-ready library for implementing the Google Agent-to-Agent (A2A) protocol with full support for the Model Context Protocol (MCP).

    It enables the creation of an interoperable ecosystem of AI agents that can collaborate to solve complex problems. The library provides:

    • A2A Protocol Implementation: Standardized communication formats for agent interaction.
    • MCP Support: Standardized methods for agents to access external tools and data sources.
    • Interoperability: Seamless integration between A2A agents, LangChain tools, and MCP tools.
    • Framework Agnostic: Works with Flask, FastAPI, Django, or any other Python framework.
  3. Overview of Python A2A

    main

    Python A2A is a production-ready implementation of Google's Agent-to-Agent (A2A) protocol. It is designed to build interoperable AI agent ecosystems where agents can collaborate regardless of their underlying implementation.

    Key capabilities include:

    • A2A Protocol Implementation: Standardized communication format for agent interaction.
    • MCP Integration: Support for the Model Context Protocol to allow agents to access external tools and data sources.
    • LangChain Integration: Interoperability with LangChain tools and agents.
    • Agent Discovery: Built-in registry and discovery mechanisms.
    • Agent Flow UI: A visual workflow editor for building agent networks via a drag-and-drop interface.
    • LLM Flexibility: Native support for providers like OpenAI and Anthropic.
    • Minimal Core Dependencies: The core functionality only requires the requests library.
  4. Overview of Python A2A and its core protocols

    main

    Python A2A is a production-ready library for implementing Google's Agent-to-Agent (A2A) protocol with full support for the Model Context Protocol (MCP).

    • A2A Protocol: Establishes a standard communication format that enables AI agents to interact regardless of their underlying implementation.
    • MCP (Model Context Protocol): Provides a standardized way for agents to access external tools and data sources.

    The library is framework-agnostic (works with Flask, FastAPI, Django, etc.) and supports multiple LLM providers including OpenAI, Anthropic, AWS Bedrock, and Ollama.

  5. Explore Python A2A example categories

    main

    The examples/ directory is organized into several functional categories to help you find specific implementation patterns:

    • Getting Started: Beginner-level examples for creating messages (hello_a2a.py), connecting as a client (simple_client.py), building a server (simple_server.py), and implementing function calling (function_calling.py).
    • Streaming: Real-time response implementations, ranging from basic streaming to advanced techniques like metrics tracking, LLM integration, task-based progress, and UI/distributed streaming.
    • Building Blocks: Core protocol concepts including Agent Discovery (agent cards), Messages and Conversations, the Task model, and defining Agent Skills using decorators.
    • AI-Powered Agents: Integration examples for OpenAI, Anthropic, and AWS Bedrock.
    • Agent Network: Orchestration patterns including basic/parallel workflows, smart routing, and automatic agent discovery.
    • Model Context Protocol (MCP): Extending agents with external tools via GitHub, Browserbase, or Filesystem MCP providers.
    • Complete Applications: End-to-end use cases like a Weather Assistant or an OpenAI Travel Planner.
    • Developer Tools: CLI tools, interactive documentation generation, and agent testing utilities.
  6. What is the A2A Protocol?

    main

    The Agent-to-Agent (A2A) protocol is a standard communication format (developed by Google) that allows AI agents to interact regardless of their underlying implementation. It provides a common language for exchanging information, making requests, and sharing responses.

    Key components include:

    • Messages: Units of communication.
    • Tasks: Units of work.
    • Agent Cards: Descriptions of agent capabilities.
    • Skills: Specific abilities provided by an agent.
  7. Best practices for LangChain integration

    main

    When building tools or workflows with the LangChain integration, follow these best practices:

    1. Type Hints: Use proper type hints in LangChain tools to ensure better parameter detection by agents.
    2. Error Handling: Implement robust error handling within your tools to prevent workflow crashes.
    3. Tool Documentation: Provide clear, descriptive text for tools and their parameters.
    4. Async Support: Prefer using async methods for better performance in agentic workflows.
    5. Workflow Design: Design workflows with clear, explicit data flows between A2A and LangChain components.
  8. Implement agent discovery with AgentRegistry and DiscoveryClient

    main

    Python A2A provides a discovery mechanism to allow agents to find each other in a network.

    1. AgentRegistry: A central server that maintains a registry of available agents.
    2. AgentCard: A metadata object describing an agent's name, description, URL, version, and capabilities.
    3. enable_discovery: A function used by an A2AServer to register itself with a registry.
    4. DiscoveryClient: A client used to query a registry and discover available agents.
    from python_a2a import AgentCard, A2AServer, run_server
    from python_a2a.discovery import AgentRegistry, run_registry, enable_discovery, DiscoveryClient
    
    # 1. Setup Registry
    registry = AgentRegistry(name="A2A Registry Server")
    # (Run registry in a thread using run_registry...)
    
    # 2. Create and Register an Agent
    agent_card = AgentCard(
        name="Weather Agent",
        url="http://localhost:8001",
        capabilities={"weather_forecasting": True}
    )
    agent = A2AServer(agent_card=agent_card)
    enable_discovery(agent, registry_url="http://localhost:8000")
    
    # 3. Discover Agents via Client
    client = DiscoveryClient()
    client.add_registry("http://localhost:8000")
    agents = client.discover()
    for agent in agents:
        print(f"Found {agent.name} at {agent.url}")
  9. Build a Multi-Agent System with Agent Collaboration

    main

    You can build complex systems by creating specialized agents that communicate with each other using A2AClient. In a multi-agent architecture:

    1. Specialized Agents: Define agents using the @agent decorator and inherit from A2AServer. Use the @skill decorator to expose specific capabilities (e.g., get_weather).
    2. Inter-Agent Communication: One agent can act as a client to another by initializing A2AClient("http://<other-agent-url>"). Use client.ask(query) to send requests to the specialized agent.
    3. Orchestration: Create a 'UI Agent' or 'Orchestrator Agent' that receives user input and routes requests to the appropriate specialized agents based on the query content.

    To run a multi-agent system, start each agent's server on a different port using run_server(agent, port=XXXX).

    # Example of an Orchestrator Agent routing to a specialized agent
    from python_a2a import A2AServer, A2AClient, run_server
    
    class AssistantAgent(A2AServer):
        def __init__(self):
            super().__init__()
            self.weather_client = A2AClient("http://localhost:5001")
    
        def handle_task(self, task):
            text = task.message.get("content", {}).get("text", "")
            if "weather" in text.lower():
                # Route to the weather agent
                response = self.weather_client.ask(text)
                task.artifacts = [{"parts": [{"type": "text", "text": response}]}]
            # ... set task status to COMPLETED
            return task
    
    if __name__ == "__main__":
        run_server(AssistantAgent(), port=5000)
  10. Python A2A Architecture and Design Principles

    main

    Python A2A is designed around three core principles:

    1. Protocol-first: Strict adherence to A2A and MCP specifications for interoperability.
    2. Modularity: Components are designed to be composable and replaceable.
    3. Progressive Enhancement: Start simple and add complexity only as needed.

    The architecture consists of several key components: Models (data structures), Client (messaging/networks), Server (agent construction), Discovery (registry/discovery), MCP (Model Context Protocol tools), LangChain (integration bridge), Workflow (orchestration), Utils, and CLI.

  11. Manage multiple MCP servers in a single agent

    main

    You can connect to multiple MCP servers simultaneously by providing a configuration dictionary to a FastMCPAgent. This allows an agent to orchestrate tools from different sources (e.g., a local calculator, a remote database, and a filesystem server) in a single task.

    # Connect to multiple MCP servers simultaneously
    mcp_config = {
        "calculator": {"command": ["python", "calc_server.py"]},
        "database": {"url": "https://db.example.com/mcp/sse"},
        "files": {"command": ["node", "file_server.js"]}
    }
    
    class MultiToolAgent(A2AServer, FastMCPAgent):
        def __init__(self):
            FastMCPAgent.__init__(self, mcp_servers=mcp_config)
        
        async def solve_complex_task(self, query):
            # Use tools from different servers
            calc_result = await self.call_mcp_tool("calculator", "add", a=5, b=3)
            data = await self.call_mcp_tool("database", "query", sql="SELECT * FROM users")
            file_content = await self.call_mcp_tool("files", "read", path="/config.json")
            
            return self._combine_results(calc_result, data, file_content)
  12. Discover agents using AgentRegistry and DiscoveryClient

    main

    Python A2A provides a discovery mechanism for agent ecosystems.

    1. AgentRegistry: A central server that stores AgentCard information.
    2. AgentCard: A metadata object containing an agent's name, description, URL, version, and capabilities.
    3. enable_discovery: A function used on an A2AServer to register it with a registry.
    4. DiscoveryClient: A client used to connect to a registry and discover available agents.
    from python_a2a import AgentCard, A2AServer, run_server
    from python_a2a.discovery import AgentRegistry, run_registry, enable_discovery, DiscoveryClient
    
    # 1. Setup Registry
    registry = AgentRegistry(name="A2A Registry Server")
    # run_registry(registry, host="0.0.0.0", port=8000)
    
    # 2. Create Agent with Card
    agent_card = AgentCard(
        name="Weather Agent",
        url="http://localhost:8001",
        capabilities={"weather_forecasting": True}
    )
    agent = A2AServer(agent_card=agent_card)
    
    # 3. Enable Discovery (registers agent to registry)
    discovery_client = enable_discovery(agent, registry_url="http://localhost:8000")
    
    # 4. Use DiscoveryClient to find agents
    client = DiscoveryClient()
    client.add_registry("http://localhost:8000")
    agents = client.discover()
    for agent in agents:
        print(f"{agent.name} at {agent.url}")