Phidata代理开发简明教程

LIBRARY Dec 30, 2024

你看,即使是强大的 LLM 也并不总是无所不知(尽管他们可能表现得像个万事通!)。就像所有伟大的事物一样,他们有时也需要外界的一点帮助——在推理、数学、编码或任何复杂任务中需要额外的帮助,而不仅仅是“精心设计的文字”。这就是代理发挥作用的地方。

有很多工具可以构建 LLM 代理,但并非所有工具都易于使用。今天,我们将查看一个简单但功能强大的框架 Phidata,看看它如何让使用 LLM 代理变得轻而易举!

1、Web代理:通向外部世界的窗口

LLM 通常无法访问互联网,因此让他们体验一下外部世界会立即让他们与时俱进。

例如,让我们在 Python 中设置我们最喜欢的专有 LLM:

from openai import OpenAI
import os
os.environ["OPENAI_API_KEY"] = "get-your-own-api-key"

prompt = "Is there any plane crash in South Korea recently?"

client = OpenAI()

chat_completion = client.chat.completions.create(
    messages=[
        {
            "role": "user",
            "content": prompt,
        }
    ],
    model="gpt-4o",
)

## Let's print the output:
chat_completion.choices[0].message.content

GPT 4o 没有 2024 年 5 月之后的任何信息。因此,我们得到了预期的结果:

很抱歉,我无法提供有关最近事件或飞机失事的实时信息。为了找到最新的信息,我建议查看可靠的新闻来源或官方航空当局以获取最新更新。

现在,让我们使用 phidata 构建我们的 Web 代理。

web_agent = Agent(
    name="Web Agent",
    model=OpenAIChat(id="gpt-4o"),
    tools=[DuckDuckGo()],
    instructions=["Always include sources"],
    show_tool_calls=True,
    markdown=True,
)

web_agent.print_response("Is there any plane crash in South Korea recently?", stream=True)

答对了!它使用 Duckduckgo 搜索互联网并找到了最新信息。根据我的经验,这是工具最重要的应用。

2、财务代理:你自己的财务顾问

有一件事你绝对不能依赖 LLM 现有的知识库,那就是财务信息。股票价格时常发生变化,要掌握最新情况,你需要最新的数据。这就是 Phidata 介入的地方——它使用 Yahoo Finance 获取最新的财务信息,包括股票更新,因此你始终了解最新情况。

from phi.tools.yfinance import YFinanceTools

finance_agent = Agent(
    name="Finance Agent",
    role="Financial Expert who can analyze stock price",
    model=OpenAIChat(id="gpt-4o"),
    tools=[YFinanceTools(stock_price=True, analyst_recommendations=True, company_info=True)],
    instructions=["Use tables to display data"],
    show_tool_calls=True,
    markdown=True,
)

finance_agent.print_response("Based on current stock price, should I buy, hold or sell tesla stock?", stream=True)

这就是我们所得到的:

Running:                                                                                                        ┃
┃                                                                                                                 ┃
┃  • get_current_stock_price(symbol=TSLA)                                                                         ┃
┃  • get_analyst_recommendations(symbol=TSLA)                                                                     ┃
┃  • get_company_info(symbol=TSLA)                                                                                ┃
┃                                                                                                                 ┃
┃ Here's an analysis of Tesla's current stock status and recommendations:                                         ┃
┃                                                                                                                 ┃
┃                                               Current Stock Price                                               ┃
┃                                                                                                                 ┃
┃  • Tesla Inc. (TSLA): $431.66 USD                                                                               ┃
┃                                                                                                                 ┃
┃                                                Company Overview                                                 ┃
┃                                                                                                                 ┃
┃  • Market Capitalization: $1.39 Trillion USD                                                                    ┃
┃  • Sector: Consumer Cyclical                                                                                    ┃
┃  • Industry: Auto Manufacturers                                                                                 ┃
┃  • EPS (Earnings Per Share): $3.67                                                                              ┃
┃  • P/E Ratio: 117.62                                                                                            ┃
┃  • 52-Week Range: $138.8 - $488.54 USD                                                                          ┃
┃  • Average Prices:                                                                                              ┃
┃     • 50 Day: $338.59 USD                                                                                       ┃
┃     • 200 Day: $236.36 USD                                                                                      ┃
┃                                                                                                                 ┃
┃                                             Analyst Recommendations                                             ┃
┃                                                                                                                 ┃
┃ The table below summarizes recent analyst recommendations for Tesla:                                            ┃
┃                                                                                                                 ┃
┃                                                                                                                 ┃
┃   Period         Strong Buy   Buy   Hold   Sell   Strong Sell                                                   ┃
┃  ━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━                                                  ┃
┃   Current        6            13    15     8      5                                                             ┃
┃   1 Month Ago    5            13    17     8      5                                                             ┃
┃   2 Months Ago   6            12    19     7      4                                                             ┃
┃   3 Months Ago   5            13    18     7      4                                                             ┃
┃                                                                                                                 ┃
┃                                                                                                                 ┃
┃                                                   Financials                                                    ┃
┃                                                                                                                 ┃
┃  • Total Cash: $33.65 Billion USD                                                                               ┃
┃  • Free Cash Flow: $676.63 Million USD                                                                          ┃
┃  • Operating Cash Flow: $14.48 Billion USD                                                                      ┃
┃  • EBITDA: $13.24 Billion USD                                                                                   ┃
┃  • Revenue Growth: 7.8%                                                                                         ┃
┃  • Gross Margins: 18.23%                                                                                        ┃
┃  • EBITDA Margins: 13.63%                                                                                       ┃
┃                                                                                                                 ┃
┃                                                 Recommendation                                                  ┃
┃                                                                                                                 ┃
┃ Considering the current stock price of $431.66 USD, which is not far from the 52-week high of $488.54 USD, and  ┃
┃ the analyst recommendation breakdown with a predominant "hold" sentiment alongside a mix of buy and sell        ┃
┃ recommendations, it would be prudent at this moment to:                                                         ┃
┃                                                                                                                 ┃
┃  • Hold: if you are currently holding Tesla stock, monitoring market trends and waiting for clearer indicators  ┃
┃    could be beneficial.                                                                                         ┃
┃  • Buy: only if you strongly believe in Tesla's growth potential and your risk tolerance supports a high P/E    ┃
┃    ratio stock.                                                                                                 ┃
┃  • Sell: only if you are looking to take profits at a nearing high resembling the 52-week peak, and have a low  ┃
┃    risk tolerance.                                                                                              ┃
┃                                                                                                                 ┃
┃ These recommendations are highly dependent on personal risk tolerance, investment strategy, and market          ┃
┃ conditions moving forward. Consulting with a financial advisor for personalized advice     

3、代理团队:利用多个代理的力量

在现实生活中,有很多情况需要多个朋友的帮助。想象一下,你正在为寻求财务建议的人建立客户服务热线。网络代理可以帮助你收集一般信息,而财务代理可以获取股票价格。但是,当你遇到需要网络和财务代理共同合作的特定问题时会发生什么?

我有 10 万美元的存款,我想在 2025 年进行多元化投资。根据过去 10 年的数据,帮助我确定我应该在哪里投资

web_agent = Agent(
    name="Web Agent",
    role="Search the web for stock market prices",
    model=OpenAIChat(id="gpt-4o"),
    tools=[DuckDuckGo()],
    instructions=["Always include sources"],
    show_tool_calls=True,
    markdown=True,
)


finance_agent = Agent(
    name="Finance Agent",
    role="Financial Expert who can analyze stock price",
    model=OpenAIChat(id="gpt-4o"),
    tools=[YFinanceTools(stock_price=True, analyst_recommendations=True, company_info=True)],
    instructions=["Use tables to display data"],
    show_tool_calls=True,
    markdown=True,
)


agent_team = Agent(
    team=[web_agent, finance_agent],
    show_tool_calls=True,
    markdown=True,
)

agent_team.print_response("I have $100k savings, and I want to invest it diversely in 2025. Based on last 10 years data, help me where I should invest exactlty", stream=True)

输出如下所示:

To give you a comprehensive answer, I will:                                                                     ┃
┃                                                                                                                 ┃
┃  1 Research historical performance of various investment options over the last 10 years.                        ┃
┃  2 Provide analysis and investment recommendations based on diversification strategies.                         ┃
┃                                                                                                                 ┃
┃ Let me gather and analyze the data for you. I will consult financial data sources and come back with a          ┃
┃ comprehensive investment plan. Running:                                                                         ┃
┃                                                                                                                 ┃
┃  • transfer_task_to_web_agent(task_description=..., expected_output=A summary of historical returns for         ┃
┃    different investment types for the last 10 years., additional_information=Look for reputable financial       ┃
┃    sources and reports.)                                                                                        ┃
┃  • transfer_task_to_finance_agent(task_description=..., expected_output=..., additional_information=Consider    ┃
┃    factors like historical performance, risk, and potential growth.)                                            ┃
┃                                                                                                                 ┃
┃ Based on the analysis of historical performance data and the development of a diversified investment strategy,  ┃
┃ here's where you should consider investing your $100,000 in 2025.                                               ┃
┃                                                                                                                 ┃
┃                                Summary of Historical Performance (Last 10 Years)                                ┃
┃                                                                                                                 ┃
┃  1 Stocks:                                                                                                      ┃
┃     • Average Annual Returns: 9-10% (S&P 500)                                                                   ┃
┃     • Highlights: Robust performance, though volatile.                                                          ┃
┃  2 Bonds:                                                                                                       ┃
┃     • Average Annual Returns: 4-5%                                                                              ┃
┃     • Highlights: Stability with lower returns than stocks, affected by interest rates.                         ┃
┃  3 Real Estate:                                                                                                 ┃
┃     • Average Annual Returns: 3-4%                                                                              ┃
┃     • Highlights: Moderate returns; acts as an inflation hedge.                                                 ┃
┃  4 Commodities:                                                                                                 ┃
┃     • Variability: Performance linked to macroeconomic factors with significant volatility.                     ┃
┃                                                                                                                 ┃
┃                                   Recommended Diversified Portfolio for 2025                                    ┃
┃                                                                                                                 ┃
┃ Here's the diversification strategy for investing $100,000 in 2025:                                             ┃
┃                                                                                                                 ┃
┃                                                                                                                 ┃
┃   Asset Type                Allocation Percentage   Notes                                                       ┃
┃  ━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━  ┃
┃   Stocks (Equities)         50%                     Focus on sectors like technology and green energy.          ┃
┃   Bonds (Fixed Income)      25%                     Offers stability, important for risk mitigation.            ┃
┃   Real Estate               15%                     A tangible asset and an inflation hedge.                    ┃
┃   Alternative Investments   10%                     Includes commodities and potentially cryptocurrency or      ┃
┃                                                     tech startups.                                              ┃
┃                                                                                                                 ┃
┃                                                                                                                 ┃
┃                                                   Rationale:                                                    ┃
┃                                                                                                                 ┃
┃  • Stocks provide the highest growth potential but require careful selection due to higher risk.                ┃
┃  • Bonds ensure stability and provide a steady income.                                                          ┃
┃  • Real Estate serves as a hedge against inflation, with potential for steady growth, especially in areas with  ┃
┃    population growth.                                                                                           ┃
┃  • Alternative Investments add diversification and the opportunity to capitalize on emerging and unconventional ┃
┃    markets.                                                                                                     ┃
┃                                                                                                                 ┃
┃ This strategic allocation aims to balance risk and return, leveraging the strength of different asset classes.  ┃
┃ For in-depth analysis of specific stocks or real-time market conditions, you may need to consult with further   ┃
┃ financial advisors or update the data closer to your investment date.                                           ┃
┃                                                                                                                 ┃
┃ Sources include historical financial studies and insights from Quantified Strategies, BlackRock, and industry   ┃
┃ performance reports.                                                                                            ┃
┃                       

在输出中,请注意以下部分:transfer_task_to_web_agent… 过去 10 年不同投资类型的历史回报摘要……和 transfer_task_to_finance_agent…考虑历史表现、风险和潜在增长等因素……这表明该程序寻求两个代理来获得全面的答案。

4、Phidata 的其他代理

查看此处提供的众多工具。话虽如此,并非所有工具都能完美运行,有些工具还不完全可靠。Phidata 仍在进行中,但如果你想以更实际的方式构建完全可靠的解决方案,并且不依赖框架,请继续关注——我很快会分享一个关于从头开始创建 LLM 代理的详细教程!


原文链接:Building LLM Agents with Phidata: Let’s begin the fun

汇智网翻译整理,转载请标明出处

Tags