MarkTechPost@AI 17小时前
Getting Started with Agent Communication Protocol (ACP): Build a Weather Agent with Python
index_new5.html
../../../zaker_core/zaker_tpl_static/wap/tpl_guoji1.html

 

本文介绍了Agent Communication Protocol (ACP) 协议,这是一个开放标准,旨在促进AI agent、应用程序和人类之间的无缝通信。文章通过构建一个简单的天气查询Agent,演示了如何使用ACP协议。读者将学习如何设置ACP服务器和客户端,并使用Python编写代码来获取伦敦的天气信息。文章详细介绍了安装依赖、创建Agent、运行服务器和客户端的步骤,帮助读者快速上手ACP,并了解其在AI系统互操作性方面的应用。

💡ACP是一个开放标准,旨在促进AI agent、应用程序和人类之间的无缝通信。它通过提供统一的RESTful API,支持多模态通信、同步和异步消息传递、实时流、有状态和无状态的agent交互以及agent发现和长任务执行。

⚙️文章通过构建一个天气查询Agent来演示ACP的使用。首先,需要安装acp、acp-sdk 和 beeai-framework 和 httpx库。然后,创建一个ACP服务器,定义一个名为london_weather_agent的agent,该agent通过调用Open-Meteo API来获取伦敦的天气信息。

💻为了与ACP服务器交互,文章还创建了一个ACP客户端。客户端使用ACP SDK连接到本地运行的london_weather_agent,并发送一个同步消息来请求天气信息。 客户端接收到来自agent的响应后,会打印出伦敦的当前天气信息。

🚀运行服务器和客户端。启动服务器后,ACP agent将通过http://localhost:8000提供服务。用户可以使用curl命令验证agent是否正在运行。然后运行客户端,客户端将向服务器发送请求,并接收到agent返回的伦敦天气信息。

The Agent Communication Protocol (ACP) is an open standard designed to enable seamless communication between AI agents, applications, and humans. As AI systems are often developed using diverse frameworks and infrastructures, they can end up isolated and incompatible, limiting their ability to collaborate. ACP addresses this fragmentation by offering a unified RESTful API that facilitates:

In this tutorial, we’ll take our first steps with ACP by building a basic server that provides London’s weather information and a simple client that can interact with it.

Setting up the dependencies

Installing the libraries

pip install acp acp-sdk beeai-framework httpx

Creating the ACP Server

We’ll begin by setting up the ACP server, starting with the creation of an agent.py file.

We’ll begin by importing the necessary libraries. To fetch London’s weather data, we’ll use the httpx library to make a request to the Open‑Meteo API.

import asynciofrom collections.abc import AsyncGeneratorimport httpx                              from acp_sdk.models import Message, MessagePartfrom acp_sdk.server import Context, RunYield, RunYieldResume, Serverserver = Server()

Next, we’ll define an asynchronous helper function called get_london_weather that retrieves the current weather in London using the Open‑Meteo API. This function sends a request with London’s coordinates and returns a formatted weather summary including temperature, wind speed, and weather condition code.

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']}."    )

This code defines an ACP-compatible agent using the @server.agent() decorator. The london_weather_agent function handles incoming messages by first yielding a thought message, then asynchronously fetching the current weather in London using the get_london_weather() helper. The weather data is then returned as a plain text message. Finally, server.run() starts the ACP server and makes the agent available to handle requests

@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 server

Next, we’ll run the agent.py file to start the server. Once running, the ACP agent will be available to handle requests at http://localhost:8000

To verify that your agent is up and running, open a new terminal and execute the following curl command:

curl http://localhost:8000/agents

If everything is working correctly, you’ll receive a JSON response listing your agent, confirming that it’s available and ready to handle requests.

{    "agents": [        {            "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 Client

We will now create an ACP client (client.py) to interact with our server. 

This client script uses the ACP SDK to connect to the locally running london_weather_agent via the ACP server at http://localhost:8000. It sends a synchronous message asking for the weather using the run_sync method. Once the agent responds, the script prints out the returned weather details.

import asynciofrom acp_sdk.client import Clientfrom acp_sdk.models import Message, MessagePartasync 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, run the following command to send request to our ACP server

You should see a response from the server containing the current weather in London, returned by the london_weather_agent.

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

Check out the Codes. All credit for this research goes to the researchers of this project. Also, feel free to follow us on Twitter, Youtube and Spotify and don’t forget to join our 100k+ ML SubReddit and Subscribe to our Newsletter.

The post Getting Started with Agent Communication Protocol (ACP): Build a Weather Agent with Python appeared first on MarkTechPost.

Fish AI Reader

Fish AI Reader

AI辅助创作,多种专业模板,深度分析,高质量内容生成。从观点提取到深度思考,FishAI为您提供全方位的创作支持。新版本引入自定义参数,让您的创作更加个性化和精准。

FishAI

FishAI

鱼阅,AI 时代的下一个智能信息助手,助你摆脱信息焦虑

联系邮箱 441953276@qq.com

相关标签

ACP Agent Communication Protocol AI Agent Python
相关文章