
在我之前的文章 "Elastic AI agent builder 介绍(一)",我详细地介绍了如何在 Kibana 中创建 tools 及 agents。在今天的文章里,我讲详细地介绍如何在 Python 应用里访问这些 agents。我们可以参考文章 "开始使用 Elastic Agent Builder 和 Microsoft Agent Framework"。
安装
我们首先参考文章 "Elastic AI agent builder 介绍(一)" 来进行安装。我们也需要按照这个章节来创建一个叫做 find_the_cheapest_ticket_from_cn_us 的 agent。

我们可以在 Agents 界面中进行如上的查询。
下载代码
接下来,我们下载已经创建好的代码:
bash
`git clone https://github.com/liu-xiao-guo/ai_agent_builder`AI写代码
然后我们进入到项目的根目录中,并创建一个叫做 .env 的文件:
.env
ini
`
1. ES_AGENT_URL=http://localhost:5601/api/agent_builder/a2a
2. ES_API_KEY=WnJwR3RKb0JGQVVCVjdnb29yUkI6RHotbGZBTmJzMDJWUWszbTAtbDVjQQ==
3. AGENT_ID=find_the_cheapest_ticket_from_cn_us
`AI写代码
我们需要根据自己的配置进行相应的修改。我们可以通过如下的方法来得到你自己的 a2a 地址:



针对我的情况,上面的地址是:
bash
`http://localhost:5601/api/agent_builder/mcp`AI写代码
很显然,上面的地址是给 MCP 而用的。我们需要把上面的 mcp 换成 a2a,这样它的地址就是:
bash
`http://localhost:5601/api/agent_builder/a2a`AI写代码
接下来,我们来创建一个用于我们访问 Elasticsearch 的 API key:




拷贝上面的 key。这样我们就完成了我们的 API key 申请。
另外,我们需要填入我们想要访问的 agent ID,比如上面的 find_the_cheapest_ticket_from_cn_us
接下来,我们需要使用如下的命令来安装所需要的包:
go
`pip install -r requirements.txt` AI写代码
运行代码
我们的代码非常简单:
access_agents.py
ini
`
1. import asyncio
2. from dotenv import load_dotenv
3. import httpx
4. import os
5. from a2a.client import A2ACardResolver
6. from agent_framework.a2a import A2AAgent
9. async def main():
10. load_dotenv()
11. a2a_agent_host = os.getenv("ES_AGENT_URL")
12. a2a_agent_key = os.getenv("ES_API_KEY")
13. agent_id = os.getenv("AGENT_ID")
15. print(f"Connection to Elastic A2A agent at: {a2a_agent_host}")
17. custom_headers = {"Authorization": f"ApiKey {a2a_agent_key}"}
19. async with httpx.AsyncClient(timeout=60.0, headers=custom_headers) as http_client:
20. # Resolve the A2A Agent Card
21. resolver = A2ACardResolver(httpx_client=http_client, base_url=a2a_agent_host)
22. agent_card = await resolver.get_agent_card(
23. relative_card_path=f"/{agent_id}.json"
24. )
25. print(f"Found Agent: {agent_card.name} - {agent_card.description}")
27. # Use the Agent
28. agent = A2AAgent(
29. name=agent_card.name,
30. description=agent_card.description,
31. agent_card=agent_card,
32. url=a2a_agent_host,
33. http_client=http_client,
34. )
35. prompt = input("Enter Greeting >>> ")
36. print("\nSending message to Elastic A2A agent...")
37. response = await agent.run(prompt)
38. print("\nAgent Response:")
39. for message in response.messages:
40. print(message.text)
43. if __name__ == "__main__":
44. asyncio.run(main())
`AI写代码
我们运行上面的应用:
go
`python access_agents.py` AI写代码
go
`从中国到美国最便宜的机票是多少?出发城市和到达城市是什么?`AI写代码
markdown
`
1. $ pwd
2. /Users/liuxg/python/ai_agent_builder
3. $ ls
4. README.md access_agents.py requirements.txt
5. $ python access_agents.py
6. Connection to Elastic A2A agent at: http://localhost:5601/api/agent_builder/a2a
7. Found Agent: Find cheapest price from China to US - Find cheapest price from China to US
8. Enter Greeting >>> 从中国到美国最便宜的机票是多少?出发城市和到达城市是什么?
10. Sending message to Elastic A2A agent...
12. Agent Response:
13. 根据查询结果,从中国到美国最便宜的机票信息如下:
15. - **机票价格**:272.68美元
16. - **出发城市**:广州 (Guangzhou)
17. - **到达城市**:塔尔萨 (Tulsa)
`AI写代码
很显然,我们得到了我们想要的结果。
我们也可以使用英文来进行提问:
vbnet
`What is the cheapest air-ticket price from China to US? What are the origin city and the destination city?`AI写代码
markdown
`
1. $ python access_agents.py
2. Connection to Elastic A2A agent at: http://localhost:5601/api/agent_builder/a2a
3. Found Agent: Find cheapest price from China to US - Find cheapest price from China to US
4. Enter Greeting >>> What is the cheapest air-ticket price from China to US? What are the origin city and the destination city?
6. Sending message to Elastic A2A agent...
8. Agent Response:
9. Based on the flight data, the cheapest air-ticket from China to the US is:
11. - **Price**: $272.68
12. - **Origin City**: Guangzhou, China
13. - **Destination City**: Tulsa, USA
`AI写代码
如果我们想使用 gradio 来做一个网页,那么我们可以把我们的代码修改为:
access_agents_gradio.py
ini
`
1. import asyncio
2. from dotenv import load_dotenv
3. import httpx
4. import os
5. from a2a.client import A2ACardResolver
6. from agent_framework.a2a import A2AAgent
7. import gradio as gr
9. # ---------- Global variables ----------
10. a2a_agent_host = None
11. a2a_agent_key = None
12. agent_id = None
13. agent_card = None
14. custom_headers = None
17. # ---------- Initialize everything once ----------
18. async def init_agent():
19. global a2a_agent_host, a2a_agent_key, agent_id, agent_card, custom_headers
21. load_dotenv()
22. a2a_agent_host = os.getenv("ES_AGENT_URL")
23. a2a_agent_key = os.getenv("ES_API_KEY")
24. agent_id = os.getenv("AGENT_ID")
26. print(f"Connecting to Elastic A2A agent: {a2a_agent_host}")
28. custom_headers = {"Authorization": f"ApiKey {a2a_agent_key}"}
30. async with httpx.AsyncClient(timeout=60.0, headers=custom_headers) as http_client:
31. resolver = A2ACardResolver(httpx_client=http_client, base_url=a2a_agent_host)
32. agent_card = await resolver.get_agent_card(
33. relative_card_path=f"/{agent_id}.json"
34. )
35. print(f"Loaded Agent Card: {agent_card.name} - {agent_card.description}")
38. # ---------- Function that Gradio will call ----------
39. async def call_agent(prompt):
40. async with httpx.AsyncClient(timeout=60.0, headers=custom_headers) as http_client:
41. agent = A2AAgent(
42. name=agent_card.name,
43. description=agent_card.description,
44. agent_card=agent_card,
45. url=a2a_agent_host,
46. http_client=http_client,
47. )
48. response = await agent.run(prompt)
49. return "\n".join([msg.text for msg in response.messages])
52. # ---------- Gradio wrapper (sync → async) ----------
53. def gradio_handler(prompt):
54. return asyncio.run(call_agent(prompt))
57. # ---------- Launch Gradio UI ----------
58. async def launch_gradio():
59. await init_agent() # Load everything before UI starts
61. iface = gr.Interface(
62. fn=gradio_handler,
63. inputs=gr.Textbox(lines=2, label="Enter Greeting"),
64. outputs=gr.Textbox(label="Agent Response"),
65. title="Elastic A2A Agent Web UI"
66. )
67. iface.launch()
70. if __name__ == "__main__":
71. asyncio.run(launch_gradio())
`AI写代码收起代码块
go
`python access_agents_gradio.py`AI写代码

祝大家使用 AI agent builder 愉快!