首頁 > 後端開發 > Python教學 > 使用 phidata 和 Ollama 建構 I 代理

使用 phidata 和 Ollama 建構 I 代理

DDD
發布: 2024-12-17 07:29:25
原創
646 人瀏覽過

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中文網其他相關文章!

來源:dev.to
本網站聲明
本文內容由網友自願投稿,版權歸原作者所有。本站不承擔相應的法律責任。如發現涉嫌抄襲或侵權的內容,請聯絡admin@php.cn
熱門教學
更多>
最新下載
更多>
網站特效
網站源碼
網站素材
前端模板