MarkTechPost@AI 前天 14:25
Step-by-Step Guide to Create an AI agent with Google ADK
index_new5.html
../../../zaker_core/zaker_tpl_static/wap/tpl_guoji1.html

 

本文提供了一个使用Google Agent Development Kit (ADK) 构建AI agent的逐步指南。该agent能够访问财务数据,并提供公司概览和收益信息。文章详细介绍了设置依赖项、创建项目结构、编写agent代码以及运行agent的步骤。通过Alpha Vantage API获取实时财务数据,并使用get_company_overview和get_earnings两个工具来检索关键的公司财务指标,如市值、市盈率、收益报告等。最后,通过adk web命令运行agent,用户可以在浏览器中与agent进行交互。

🔑 **准备工作:** 构建AI agent需要依赖Google AI服务和Alpha Vantage API。首先,需要获取Google API Key和Alpha Vantage API Key,并安全存储。然后,通过pip安装google-adk库。

📁 **项目结构:** 项目目录结构包括一个multi_agent文件夹,其中包含__init__.py、agent.py和.env文件。在.env文件中,需要配置GOOGLE_API_KEY和ALPHA_VANTAGE_API_KEY。

🛠️ **核心工具:** agent.py定义了两个核心工具:get_company_overview和get_earnings。get_company_overview用于获取公司概览信息,如描述、行业、市值等;get_earnings用于获取公司年度和季度收益数据。

🤖 **Agent 创建:** 使用Agent类创建金融分析agent,指定其名称、模型(如gemini-2.0-flash)、描述和指令。该agent被赋予get_company_overview和get_earnings这两个工具,使其能够响应与公司财务相关的查询。

🚀 **运行与交互:** 通过在终端中运行adk web命令来启动agent,然后在浏览器中访问提供的URL(通常是http://localhost:8000)。用户可以在界面中与agent交互,agent会调用相应的工具并返回结果。

Agent Development Kit (ADK) is an open-source Python framework that helps developers build, manage, and deploy multi-agent systems. It’s designed to be modular and flexible, making it easy to use for both simple and complex agent-based applications.

In this tutorial, we’ll create a simple AI agent using ADK. The agent will have access to two tools:

Step 1: Setting up the dependencies

Google API Key

To use Google’s AI services, you’ll need an API key:

AlphaVantage API Key

For accessing financial data, we’ll use the Alpha Vantage API:

Python Libraries

We only need one package:

Step 2: Creating the Folder structure

Set up your project folder with the following structure:

parent_folder/│└───multi_agent/    ├── __init__.py    ├── agent.py    └── .env

__init__.py

Paste the following code into multi_agent/__init__.py:

.env

Create a .env file inside the multi_agent folder and paste the following:

GOOGLE_GENAI_USE_VERTEXAI=FALSEGOOGLE_API_KEY="<YOUR_GOOGLE_API_KEY>"ALPHA_VANTAGE_API_KEY="<YOUR_ALPHA_VANTAGE_KEY"

Replace the placeholders with your actual API keys

agent.py

Paste the following code in the agent.py file:

from google.adk.agents import Agentimport requestsimport osfrom typing import OptionalALPHA_VANTAGE_API_KEY = os.getenv("ALPHA_VANTAGE_API_KEY")def get_company_overview(symbol: str) -> dict:    """    Get comprehensive company information and financial metrics       Args:        symbol: Stock ticker symbol (e.g., IBM)       Returns:        dict: Company overview data or error    """    if not ALPHA_VANTAGE_API_KEY:        return {"status": "error", "error": "Missing API key"}       base_url = "https://www.alphavantage.co/query"    params = {        "function": "OVERVIEW",        "symbol": symbol,        "apikey": ALPHA_VANTAGE_API_KEY    }       try:        response = requests.get(base_url, params=params)        response.raise_for_status()        data = response.json()               if "Error Message" in data:            return {"status": "error", "error": data["Error Message"]}                   # Filter key metrics        key_metrics = {            "Description": data.get("Description"),            "Sector": data.get("Sector"),            "MarketCap": data.get("MarketCapitalization"),            "PERatio": data.get("PERatio"),            "ProfitMargin": data.get("ProfitMargin"),            "52WeekHigh": data.get("52WeekHigh"),            "52WeekLow": data.get("52WeekLow")        }               return {            "status": "success",            "symbol": symbol,            "overview": key_metrics        }           except Exception as e:        return {"status": "error", "error": str(e)}def get_earnings(symbol: str) -> dict:    """    Get annual and quarterly earnings (EPS) data with analyst estimates and surprises       Args:        symbol: Stock ticker symbol (e.g., IBM)       Returns:        dict: Earnings data with estimates or error message    """    if not ALPHA_VANTAGE_API_KEY:        return {"status": "error", "error": "Missing API key"}       base_url = "https://www.alphavantage.co/query"    params = {        "function": "EARNINGS",        "symbol": symbol,        "apikey": ALPHA_VANTAGE_API_KEY    }       try:        response = requests.get(base_url, params=params)        response.raise_for_status()        data = response.json()               if "Error Message" in data:            return {"status": "error", "error": data["Error Message"]}                   # Process annual and quarterly earnings        annual_earnings = data.get("annualEarnings", [])[:5]  # Last 5 years        quarterly_earnings = data.get("quarterlyEarnings", [])[:4]  # Last 4 quarters               # Format surprise percentages        for q in quarterly_earnings:            if "surprisePercentage" in q:                q["surprise"] = f"{q['surprisePercentage']}%"               return {            "status": "success",            "symbol": symbol,            "annual_earnings": annual_earnings,            "quarterly_earnings": quarterly_earnings,            "metrics": {                "latest_eps": quarterly_earnings[0]["reportedEPS"] if quarterly_earnings else None            }        }           except Exception as e:        return {"status": "error", "error": str(e)}      root_agent = Agent(    name="Financial_analyst_agent",    model="gemini-2.0-flash",    description=(        "Agent to give company overviews with key financial metrics."    ),    instruction=(        "You are a helpful AI agent that provides company overviews and earnings information"    ),    tools=[get_company_overview, get_earnings],)

In this script, we define a financial analysis agent using the Google Agent Development Kit (ADK). The agent is designed to answer user queries by accessing real-time financial data through the Alpha Vantage API. Specifically, it exposes two tools: get_company_overview and get_earnings. The get_company_overview function retrieves key company details such as sector, market capitalization, P/E ratio, and 52-week high/low values. The get_earnings function provides both annual and quarterly earnings data, including reported EPS and surprise percentages.To create the agent, we use the Agent class from the google.adk.agents module, giving it a name, a model (e.g., Gemini 2.0 Flash), a description, and an instruction prompt. The agent is then equipped with the two tools mentioned above, allowing it to respond to questions related to company financials.

Step 3: Running the Agent

To run the agent, navigate to the parent directory of your agent project (e.g. using cd ..)

parent_folder/      ← Navigate to this directory in your terminal│└───multi_agent/    ├── __init__.py     # Initializes the module    ├── agent.py        # Contains the agent logic and tools    └── .env            # Stores your API keys securely

After navigating, run the following code:

Open the URL provided (usually http://localhost:8000 or http://127.0.0.1:8000) directly in your browser. You’ll see a simple chat interface where you can interact with your agent using the input textbox.

Additionally, you can inspect each step of the agent’s reasoning by clicking on Actions. This allows you to view:

GitHub Link

You can find the entire code along with folder structure at this link: https://github.com/mohd-arham-islam/ADK-demo

The post Step-by-Step Guide to Create an AI agent with Google ADK appeared first on MarkTechPost.

Fish AI Reader

Fish AI Reader

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

FishAI

FishAI

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

联系邮箱 441953276@qq.com

相关标签

Agent Development Kit AI Agent 金融分析 Google ADK
相关文章