搜索
首页后端开发Python教程使用 phidata 和 Ollama 构建 I 代理

Building I Agents with phidata and Ollama

在本文中,我们将探索如何使用 phidata 和 Ollama 本地法学硕士创建用于网络搜索、财务分析、推理和检索增强生成的 AI 代理。代码使用llama3.2模型。如果您想使用不同的模型,则需要下载您要使用的模型并替换代码中的 model_id 变量。

什么是Phidata?

用于构建、发布和监控代理系统的开源平台。

https://www.phidata.com/

奥拉玛是什么?

Ollama 是一个平台和工具集,旨在简化本地大语言模型 (LLM) 的部署和使用。

https://ollama.ai/

在本文中,我们将使用 llama3.2 模型。

ollama pull llama3.2

什么是紫外线?

一个非常快的 Python 包和项目管理器,用 Rust 编写。
https://github.com/astral-sh/uv

如果不想使用uv,可以使用pip代替uv。然后你需要使用 pip install 而不是 uv add。

如何安装紫外线

https://docs.astral.sh/uv/getting-started/installation/

创建项目文件夹

如果您决定使用 pip,则需要创建一个项目文件夹。

uv init phidata-ollama

安装依赖项

uv add phidata ollama duckduckgo-search yfinance pypdf lancedb tantivy sqlalchemy

在本文中,我们将尝试使用 phidata 和 Ollama 创建 5 个 AI 代理。
注意:开始之前,请通过运行 ollamaserve 确保您的 ollama 服务器正在运行。

创建 Web 搜索代理

我们将创建的第一个代理是一个网络搜索代理,它将使用 DuckDuckGo 搜索引擎。

from phi.agent import Agent
from phi.model.ollama import Ollama
from phi.tools.duckduckgo import DuckDuckGo

model_id = "llama3.2"
model = Ollama(id=model_id)

web_agent = Agent(
    name="Web Agent",
    model=model,
    tools=[DuckDuckGo()],
    instructions=["Always include sources"],
    show_tool_calls=True,
    markdown=True,
)
web_agent.print_response("Tell me about OpenAI Sora?", stream=True)

输出:

┏━ Message ━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━┓
┃                                                                         ┃
┃ Tell me about OpenAI Sora?                                              ┃
┃                                                                         ┃
┗━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━┛
┏━ Response (12.0s) ━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━┓
┃                                                                         ┃
┃                                                                         ┃
┃  • Running: duckduckgo_news(query=OpenAI Sora)                          ┃
┃                                                                         ┃
┃ OpenAI's Sora is a video-generating model that has been trained on      ┃
┃ copyrighted content, which has raised concerns about its legality.      ┃
┃ According to TechCrunch, it appears that OpenAI trained Sora on game    ┃
┃ content, which could be a problem. Additionally, MSN reported that the  ┃
┃ model doesn't feel like the game-changer it was supposed to be.         ┃
┃                                                                         ┃
┃ In other news, Yahoo reported that when asked to generate gymnastics    ┃
┃ videos, Sora produces horrorshow videos with whirling and morphing      ┃
┃ limbs. A lawyer told ExtremeTech that it's "overwhelmingly likely" that ┃
┃ copyrighted materials are included in Sora's training dataset.          ┃
┃                                                                         ┃
┃ Geeky Gadgets reviewed OpenAI's Sora, stating that while it is included ┃
┃ in the 0/month Pro Plan, its standalone value for video generation   ┃
┃ is less clear compared to other options.                                ┃
┃                                                                         ┃
┗━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━┛

创建财务代理

我们将创建的第二个代理是一个财务代理,它将使用 yfinance 工具。

from phi.agent import Agent
from phi.model.ollama import Ollama
from phi.tools.yfinance import YFinanceTools

model_id = "llama3.2"
model = Ollama(id=model_id)

finance_agent = Agent(
    name="Finance Agent",
    model=model,
    tools=[YFinanceTools(stock_price=True, analyst_recommendations=True, company_info=True, company_news=True)],
    instructions=["Use tables to display data"],
    show_tool_calls=True,
    markdown=True,
)
finance_agent.print_response("Summarize analyst recommendations for NVDA", stream=True)

输出:

┏━ Message ━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━┓
┃                                                                         ┃
┃ Summarize analyst recommendations for NVDA                              ┃
┃                                                                         ┃
┗━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━┛
┏━ Response (3.9s) ━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━┓
┃                                                                         ┃
┃                                                                         ┃
┃  • Running: get_analyst_recommendations(symbol=NVDA)                    ┃
┃                                                                         ┃
┃ Based on the analyst recommendations, here is a summary:                ┃
┃                                                                         ┃
┃  • The overall sentiment is bullish, with 12 strong buy and buy         ┃
┃    recommendations.                                                     ┃
┃  • There are no strong sell or sell recommendations.                    ┃
┃  • The average price target for NVDA is around 0-0.               ┃
┃  • Analysts expect NVDA to continue its growth trajectory, driven by    ┃
┃    its strong products and services in the tech industry.               ┃
┃                                                                         ┃
┃ Please note that these recommendations are subject to change and may    ┃
┃ not reflect the current market situation. It's always a good idea to do ┃
┃ your own research and consult with a financial advisor before making    ┃
┃ any investment decisions.                                               ┃
┃                                                                         ┃
┗━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━┛

创建代理团队

我们将创建的第三个代理是一个代理团队,它将使用 DuckDuckGo 搜索引擎和 YFinance 工具。

from phi.agent import Agent
from phi.model.ollama import Ollama
from phi.tools.duckduckgo import DuckDuckGo
from phi.tools.yfinance import YFinanceTools

web_instructions = 'Always include sources'
finance_instructions = 'Use tables to display data'

model_id = "llama3.2"
model = Ollama(id=model_id)

web_agent = Agent(
    name="Web Agent",
    role="Search the web for information",
    model=model,
    tools=[DuckDuckGo()],
    instructions=[web_instructions],
    show_tool_calls=True,
    markdown=True,
)

finance_agent = Agent(
    name="Finance Agent",
    role="Get financial data",
    model=model,
    tools=[YFinanceTools(stock_price=True, analyst_recommendations=True, company_info=True)],
    instructions=[finance_instructions],
    show_tool_calls=True,
    markdown=True,
)

agent_team = Agent(
    model=model,
    team=[web_agent, finance_agent],
    instructions=[web_instructions, finance_instructions],
    show_tool_calls=True,
    markdown=True,
)

agent_team.print_response("Summarize analyst recommendations and share the latest news for NVDA", stream=True)

创建推理代理

我们将创建的第四个代理是一个将使用任务的推理代理。

from phi.agent import Agent
from phi.model.ollama import Ollama

model_id = "llama3.2"
model = Ollama(id=model_id)

task = (
   "Three missionaries and three cannibals want to cross a river."
"There is a boat that can carry up to two people, but if the number of cannibals exceeds the number of missionaries, the missionaries will be eaten."
)

reasoning_agent = Agent(model=model, reasoning=True, markdown=True, structured_outputs=True)
reasoning_agent.print_response(task, stream=True, show_full_reasoning=True)

输出:

┏━ Message ━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━┓
┃                                                                         ┃
┃ Three missionaries and three cannibals want to cross a river.There is a ┃
┃ boat that can carry up to two people, but if the number of cannibals    ┃
┃ exceeds the number of missionaries, the missionaries will be eaten.     ┃
┃                                                                         ┃
┗━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━┛
[Reasoning steps and output as in the original document]

创建 RAG 代理

我们将创建的第五个代理是 RAG 代理,它将使用 PDF 知识库和 LanceDB 矢量数据库。

from phi.agent import Agent
from phi.model.openai import OpenAIChat
from phi.embedder.openai import OpenAIEmbedder
from phi.embedder.ollama import OllamaEmbedder

from phi.model.ollama import Ollama
from phi.knowledge.pdf import PDFUrlKnowledgeBase
from phi.vectordb.lancedb import LanceDb, SearchType

model_id = "llama3.2"
model = Ollama(id=model_id)
embeddings = OllamaEmbedder().get_embedding("The quick brown fox jumps over the lazy dog.")

knowledge_base = PDFUrlKnowledgeBase(
    urls=["https://phi-public.s3.amazonaws.com/recipes/ThaiRecipes.pdf"],
    vector_db=LanceDb(
        table_name="recipes",
        uri="tmp/lancedb",
        search_type=SearchType.vector,
        embedder=OllamaEmbedder(),
    ),
)

knowledge_base.load()

agent = Agent(
    model=model,
    knowledge=knowledge_base,
    show_tool_calls=True,
    markdown=True,
)

agent.print_response("Please tell me how to make green curry.", stream=True)

输出:

uv run rag_agent.py
WARNING  model "openhermes" not found, try pulling it first
WARNING  model "openhermes" not found, try pulling it first
INFO     Creating collection
INFO     Loading knowledge base
INFO     Reading:
         https://phi-public.s3.amazonaws.com/recipes/ThaiRecipes.pdf
WARNING  model "openhermes" not found, try pulling it first
WARNING  model "openhermes" not found, try pulling it first
WARNING  model "openhermes" not found, try pulling it first
WARNING  model "openhermes" not found, try pulling it first
WARNING  model "openhermes" not found, try pulling it first
WARNING  model "openhermes" not found, try pulling it first
WARNING  model "openhermes" not found, try pulling it first
WARNING  model "openhermes" not found, try pulling it first
WARNING  model "openhermes" not found, try pulling it first
WARNING  model "openhermes" not found, try pulling it first
WARNING  model "openhermes" not found, try pulling it first
WARNING  model "openhermes" not found, try pulling it first
WARNING  model "openhermes" not found, try pulling it first
WARNING  model "openhermes" not found, try pulling it first
INFO     Added 14 documents to knowledge base
WARNING  model "openhermes" not found, try pulling it first
ERROR    Error searching for documents: list index out of range
┏━ Message ━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━┓
┃                                                                         ┃
┃ Please tell me how to make green curry.                                 ┃
┃                                                                         ┃
┗━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━┛
┏━ Response (5.4s) ━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━┓
┃                                                                         ┃
┃                                                                         ┃
┃  • Running: search_knowledge_base(query=green curry recipe)             ┃
┃                                                                         ┃
┃ ┏━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━┓ ┃
┃ ┃                         Green Curry Recipe                          ┃ ┃
┃ ┗━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━┛ ┃
┃                                                                         ┃
┃ ** Servings: 4-6 people**                                               ┃
┃                                                                         ┃
┃ Ingredients:                                                            ┃
┃                                                                         ┃
┃  • 2 tablespoons vegetable oil                                          ┃
┃  • 2 cloves garlic, minced                                              ┃
┃  • 1 tablespoon grated fresh ginger                                     ┃
┃  • 2 tablespoons Thai red curry paste                                   ┃
┃  • 2 cups coconut milk                                                  ┃
┃  • 1 cup mixed vegetables (such as bell peppers, bamboo shoots, and     ┃
┃    Thai eggplant)                                                       ┃
┃  • 1 pound boneless, skinless chicken breasts or thighs, cut into       ┃
┃    bite-sized pieces                                                    ┃
┃  • 2 tablespoons fish sauce                                             ┃
┃  • 1 tablespoon palm sugar                                              ┃
┃  • 1/4 teaspoon ground white pepper                                     ┃
┃  • Salt to taste                                                        ┃
┃  • Fresh basil leaves for garnish                                       ┃
┃                                                                         ┃
┃ Instructions:                                                           ┃
┃                                                                         ┃
┃  1 Prepare the curry paste: In a blender or food processor, combine the ┃
┃    curry paste, garlic, ginger, fish sauce, palm sugar, and white       ┃
┃    pepper. Blend until smooth.                                          ┃
┃  2 Heat oil in a pan: Heat the oil in a large skillet or Dutch oven     ┃
┃    over medium-high heat.                                               ┃
┃  3 Add the curry paste: Pour the blended curry paste into the hot oil   ┃
┃    and stir constantly for 1-2 minutes, until fragrant.                 ┃
┃  4 Add coconut milk: Pour in the coconut milk and bring the mixture to  ┃
┃    a simmer.                                                            ┃
┃  5 Add vegetables and chicken: Add the mixed vegetables and chicken     ┃
┃    pieces to the pan. Stir gently to combine.                           ┃
┃  6 Reduce heat and cook: Reduce the heat to medium-low and let the      ┃
┃    curry simmer, uncovered, for 20-25 minutes or until the chicken is   ┃
┃    cooked through and the sauce has thickened.                          ┃
┃  7 Season with salt and taste: Season the curry with salt to taste.     ┃
┃    Serve hot garnished with fresh basil leaves.                         ┃
┃                                                                         ┃
┃ Tips and Variations:                                                    ┃
┃                                                                         ┃
┃  • Adjust the level of spiciness by using more or less Thai red curry   ┃
┃    paste.                                                               ┃
┃  • Add other protein sources like shrimp, tofu, or tempeh for a         ┃
┃    vegetarian or vegan option.                                          ┃
┃  • Experiment with different vegetables, such as zucchini or carrots,   ┃
┃    to add variety.                                                      ┃
┃                                                                         ┃
┃ Tools Used: Python                                                      ┃
┃                                                                         ┃
┗━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━┛

结论

在本文中,我们探讨了如何使用 phidata 和 Ollama 本地法学硕士创建用于网络搜索、财务分析、推理和检索增强生成的 AI 代理。

以上是使用 phidata 和 Ollama 构建 I 代理的详细内容。更多信息请关注PHP中文网其他相关文章!

声明
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系admin@php.cn
如何使用Python查找文本文件的ZIPF分布如何使用Python查找文本文件的ZIPF分布Mar 05, 2025 am 09:58 AM

本教程演示如何使用Python处理Zipf定律这一统计概念,并展示Python在处理该定律时读取和排序大型文本文件的效率。 您可能想知道Zipf分布这个术语是什么意思。要理解这个术语,我们首先需要定义Zipf定律。别担心,我会尽量简化说明。 Zipf定律 Zipf定律简单来说就是:在一个大型自然语言语料库中,最频繁出现的词的出现频率大约是第二频繁词的两倍,是第三频繁词的三倍,是第四频繁词的四倍,以此类推。 让我们来看一个例子。如果您查看美国英语的Brown语料库,您会注意到最频繁出现的词是“th

我如何使用美丽的汤来解析HTML?我如何使用美丽的汤来解析HTML?Mar 10, 2025 pm 06:54 PM

本文解释了如何使用美丽的汤库来解析html。 它详细介绍了常见方法,例如find(),find_all(),select()和get_text(),以用于数据提取,处理不同的HTML结构和错误以及替代方案(SEL)

python中的图像过滤python中的图像过滤Mar 03, 2025 am 09:44 AM

处理嘈杂的图像是一个常见的问题,尤其是手机或低分辨率摄像头照片。 本教程使用OpenCV探索Python中的图像过滤技术来解决此问题。 图像过滤:功能强大的工具 图像过滤器

如何使用Python使用PDF文档如何使用Python使用PDF文档Mar 02, 2025 am 09:54 AM

PDF 文件因其跨平台兼容性而广受欢迎,内容和布局在不同操作系统、阅读设备和软件上保持一致。然而,与 Python 处理纯文本文件不同,PDF 文件是二进制文件,结构更复杂,包含字体、颜色和图像等元素。 幸运的是,借助 Python 的外部模块,处理 PDF 文件并非难事。本文将使用 PyPDF2 模块演示如何打开 PDF 文件、打印页面和提取文本。关于 PDF 文件的创建和编辑,请参考我的另一篇教程。 准备工作 核心在于使用外部模块 PyPDF2。首先,使用 pip 安装它: pip 是 P

如何在django应用程序中使用redis缓存如何在django应用程序中使用redis缓存Mar 02, 2025 am 10:10 AM

本教程演示了如何利用Redis缓存以提高Python应用程序的性能,特别是在Django框架内。 我们将介绍REDIS安装,Django配置和性能比较,以突出显示BENE

如何使用TensorFlow或Pytorch进行深度学习?如何使用TensorFlow或Pytorch进行深度学习?Mar 10, 2025 pm 06:52 PM

本文比较了Tensorflow和Pytorch的深度学习。 它详细介绍了所涉及的步骤:数据准备,模型构建,培训,评估和部署。 框架之间的关键差异,特别是关于计算刻度的

如何在Python中实现自己的数据结构如何在Python中实现自己的数据结构Mar 03, 2025 am 09:28 AM

本教程演示了在Python 3中创建自定义管道数据结构,利用类和操作员超载以增强功能。 管道的灵活性在于它能够将一系列函数应用于数据集的能力,GE

Python中的平行和并发编程简介Python中的平行和并发编程简介Mar 03, 2025 am 10:32 AM

Python是数据科学和处理的最爱,为高性能计算提供了丰富的生态系统。但是,Python中的并行编程提出了独特的挑战。本教程探讨了这些挑战,重点是全球解释

See all articles

热AI工具

Undresser.AI Undress

Undresser.AI Undress

人工智能驱动的应用程序,用于创建逼真的裸体照片

AI Clothes Remover

AI Clothes Remover

用于从照片中去除衣服的在线人工智能工具。

Undress AI Tool

Undress AI Tool

免费脱衣服图片

Clothoff.io

Clothoff.io

AI脱衣机

AI Hentai Generator

AI Hentai Generator

免费生成ai无尽的。

热门文章

R.E.P.O.能量晶体解释及其做什么(黄色晶体)
2 周前By尊渡假赌尊渡假赌尊渡假赌
仓库:如何复兴队友
4 周前By尊渡假赌尊渡假赌尊渡假赌
Hello Kitty Island冒险:如何获得巨型种子
3 周前By尊渡假赌尊渡假赌尊渡假赌

热工具

SublimeText3 Mac版

SublimeText3 Mac版

神级代码编辑软件(SublimeText3)

SublimeText3 Linux新版

SublimeText3 Linux新版

SublimeText3 Linux最新版

SecLists

SecLists

SecLists是最终安全测试人员的伙伴。它是一个包含各种类型列表的集合,这些列表在安全评估过程中经常使用,都在一个地方。SecLists通过方便地提供安全测试人员可能需要的所有列表,帮助提高安全测试的效率和生产力。列表类型包括用户名、密码、URL、模糊测试有效载荷、敏感数据模式、Web shell等等。测试人员只需将此存储库拉到新的测试机上,他就可以访问到所需的每种类型的列表。

WebStorm Mac版

WebStorm Mac版

好用的JavaScript开发工具

SublimeText3 英文版

SublimeText3 英文版

推荐:为Win版本,支持代码提示!