Getting Began with Agent Communication Protocol (ACP): Construct a Climate Agent with Python


The Agent Communication Protocol (ACP) is an open commonplace designed to allow seamless communication between AI brokers, functions, and people. As AI programs are sometimes developed utilizing various frameworks and infrastructures, they will find yourself remoted and incompatible, limiting their means to collaborate. ACP addresses this fragmentation by providing a unified RESTful API that facilitates:

  • Multimodal communication
  • Each synchronous and asynchronous messaging
  • Actual-time streaming
  • Help for stateful and stateless agent interactions
  • Discovery of brokers, whether or not on-line or offline
  • Execution of long-running duties

On this tutorial, we’ll take our first steps with ACP by constructing a primary server that gives London’s climate data and a easy consumer that may work together with it.

Establishing the dependencies

Putting in the libraries

pip set up acp acp-sdk beeai-framework httpx

Creating the ACP Server

We’ll start by establishing the ACP server, beginning with the creation of an agent.py file.

We’ll start by importing the required libraries. To fetch London’s climate knowledge, we’ll use the httpx library to make a request to the Open‑Meteo API.

import asyncio
from collections.abc import AsyncGenerator
import httpx                              

from acp_sdk.fashions import Message, MessagePart
from acp_sdk.server import Context, RunYield, RunYieldResume, Server

server = Server()

Subsequent, we’ll outline an asynchronous helper operate referred to as get_london_weather that retrieves the present climate in London utilizing the Open‑Meteo API. This operate sends a request with London’s coordinates and returns a formatted climate abstract together with temperature, wind pace, and climate situation code.

async def get_london_weather() -> str:
    """Fetch present London climate from the free Open‑Meteo API."""
    params = {
        "latitude": 51.5072,          # London coordinates
        "longitude": -0.1276,
        "current_weather": True,
        "timezone": "Europe/London"
    }
    url = "https://api.open-meteo.com/v1/forecast"

    async with httpx.AsyncClient(timeout=10) as consumer:
        resp = await consumer.get(url, params=params)
        resp.raise_for_status()
        cw = resp.json()["current_weather"]

    return (
        f"Climate in London: {cw['temperature']} °C, "
        f"wind {cw['windspeed']} km/h, code {cw['weathercode']}."
    )

This code defines an ACP-compatible agent utilizing the @server.agent() decorator. The london_weather_agent operate handles incoming messages by first yielding a thought message, then asynchronously fetching the present climate in London utilizing the get_london_weather() helper. The climate knowledge is then returned as a plain textual content message. Lastly, server.run() begins the ACP server and makes the agent out there to deal with requests

@server.agent()
async def london_weather_agent(
    enter: checklist[Message], context: Context
) -> AsyncGenerator[RunYield, RunYieldResume]:
    """Returns present London climate."""
    for _ in enter:
        yield {"thought": "Fetching London climate..."}
        climate = await get_london_weather()
        yield Message(
            position="agent",
            components=[MessagePart(content=weather, content_type="text/plain")]
        )

server.run()

Operating the server

Subsequent, we’ll run the agent.py file to start out the server. As soon as operating, the ACP agent can be out there to deal with requests at http://localhost:8000

To confirm that your agent is up and operating, open a brand new terminal and execute the next curl command:

curl http://localhost:8000/brokers

If all the pieces is working appropriately, you’ll obtain a JSON response itemizing your agent, confirming that it’s out there and able to deal with requests.

{
    "brokers": [
        {
            "name": "london_weather_agent",
            "description": "Returns current London weather.",
            "metadata": {
                "annotations": null,
                "documentation": null,
                "license": null,
                "programming_language": null,
                "natural_languages": null,
                "framework": null,
                "capabilities": null,
                "domains": null,
                "tags": null,
                "created_at": null,
                "updated_at": null,
                "author": null,
                "contributors": null,
                "links": null,
                "dependencies": null,
                "recommended_models": null
            },
            "input_content_types": [
                "*/*"
            ],
            "output_content_types": [
                "*/*"
            ]
        }
    ]
}

Creating the ACP Shopper

We are going to now create an ACP consumer (consumer.py) to work together with our server. 

This consumer script makes use of the ACP SDK to hook up with the domestically operating london_weather_agent through the ACP server at http://localhost:8000. It sends a synchronous message asking for the climate utilizing the run_sync technique. As soon as the agent responds, the script prints out the returned climate particulars.

import asyncio

from acp_sdk.consumer import Shopper
from acp_sdk.fashions import Message, MessagePart


async def call_london_weather_agent() -> None:
    async with Shopper(base_url="http://localhost:8000") as consumer:
        run = await consumer.run_sync(
            agent="london_weather_agent",
            enter=[
                Message(
                    parts=[MessagePart(content="Tell me the weather", content_type="text/plain")]
                )
            ],
        )

        print("Response from london_weather_agent:")
        for message in run.output:
            for half in message.components:
                print("-", half.content material)


if __name__ == "__main__":
    asyncio.run(call_london_weather_agent())

Operating the Shopper

In one other terminal, run the next command to ship request to our ACP server

You need to see a response from the server containing the present climate in London, returned by the london_weather_agent.

Response from london_weather_agent:                                                     
- Climate in London: 20.8 °C, wind 10.1 km/h, code 3.

Take a look at the Codes. All credit score for this analysis goes to the researchers of this mission. Additionally, be happy to observe us on Twitter, Youtube and Spotify and don’t neglect to affix our 100k+ ML SubReddit and Subscribe to our Newsletter.


I’m a Civil Engineering Graduate (2022) from Jamia Millia Islamia, New Delhi, and I’ve a eager curiosity in Knowledge Science, particularly Neural Networks and their software in varied areas.

Leave a Reply

Your email address will not be published. Required fields are marked *