<RETURN_TO_BASE

Build a Weather Agent with Python Using the Agent Communication Protocol (ACP)

Discover how to create a weather agent in Python using the Agent Communication Protocol (ACP), enabling smooth AI agent communication and weather data fetching.

Understanding Agent Communication Protocol (ACP)

ACP is an open standard that allows AI agents, applications, and humans to communicate seamlessly despite differences in frameworks and infrastructures. It unifies various communication modes through a RESTful API, supporting multimodal communication, synchronous and asynchronous messaging, real-time streaming, stateful and stateless interactions, agent discovery, and execution of long-running tasks.

Setting Up the Environment

To start building an ACP agent, install the required Python libraries:

pip install acp acp-sdk beeai-framework httpx

Creating the ACP Server

Create a file named agent.py and import necessary libraries, including httpx for fetching weather data from the Open-Meteo API.

import asyncio
from collections.abc import AsyncGenerator
import httpx                              
 
from acp_sdk.models import Message, MessagePart
from acp_sdk.server import Context, RunYield, RunYieldResume, Server
 
server = Server()

Define an asynchronous helper function get_london_weather to fetch current weather data for London:

async def get_london_weather() -> str:
    """Fetch current London weather 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 client:
        resp = await client.get(url, params=params)
        resp.raise_for_status()
        cw = resp.json()["current_weather"]
 
    return (
        f"Weather in London: {cw['temperature']} °C, "
        f"wind {cw['windspeed']} km/h, code {cw['weathercode']}."
    )

Use the @server.agent() decorator to define the ACP agent that processes incoming messages and returns weather information:

@server.agent()
async def london_weather_agent(
    input: list[Message], context: Context
) -> AsyncGenerator[RunYield, RunYieldResume]:
    """Returns current London weather."""
    for _ in input:
        yield {"thought": "Fetching London weather..."}
        weather = await get_london_weather()
        yield Message(
            role="agent",
            parts=[MessagePart(content=weather, content_type="text/plain")]
        )
 
server.run()

Running the ACP Server

Start the server by running:

python agent.py

Verify the server is running by querying available agents:

curl http://localhost:8000/agents

The server returns a JSON list confirming the london_weather_agent is ready.

Creating the ACP Client

Create a client.py script to interact with the ACP server. This client sends a synchronous message requesting weather data:

import asyncio
 
from acp_sdk.client import Client
from acp_sdk.models import Message, MessagePart
 
 
async def call_london_weather_agent() -> None:
    async with Client(base_url="http://localhost:8000") as client:
        run = await client.run_sync(
            agent="london_weather_agent",
            input=[
                Message(
                    parts=[MessagePart(content="Tell me the weather", content_type="text/plain")]
                )
            ],
        )
 
        print("Response from london_weather_agent:")
        for message in run.output:
            for part in message.parts:
                print("-", part.content)
 
 
if __name__ == "__main__":
    asyncio.run(call_london_weather_agent())

Running the Client

In another terminal, execute:

python client.py

You should receive the current London weather information from the agent, for example:

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

This tutorial demonstrates how ACP enables building interoperable AI agents easily, allowing developers to focus on functionality without worrying about communication complexities.

🇷🇺

Сменить язык

Читать эту статью на русском

Переключить на Русский