suchen
HeimBackend-EntwicklungPython-TutorialAufbau I Agenten mit Phidata und Ollama

Building I Agents with phidata and Ollama

In diesem Artikel untersuchen wir, wie man KI-Agenten für die Websuche, Finanzanalyse, Argumentation und abrufgestützte Generierung mithilfe von Phidata und dem lokalen LLM von Ollama erstellt. Der Code verwendet das Modell llama3.2. Wenn Sie ein anderes Modell verwenden möchten, müssen Sie das Modell herunterladen, das Sie verwenden möchten, und die Variable model_id im Code ersetzen.

Was ist Phidat?

Eine Open-Source-Plattform zum Erstellen, Versenden und Überwachen von Agentensystemen.

https://www.phidata.com/

Was ist Ollama?

Ollama ist eine Plattform und ein Toolset, die die Bereitstellung und Verwendung lokaler großer Sprachmodelle (LLMs) vereinfachen sollen.

https://ollama.ai/

In diesem Artikel verwenden wir das Modell llama3.2.

ollama pull llama3.2

Was ist UV?

Ein extrem schneller Python-Paket- und Projektmanager, geschrieben in Rust.
https://github.com/astral-sh/uv

Wenn Sie kein UV verwenden möchten, können Sie Pip anstelle von UV verwenden. Dann müssen Sie pip install anstelle von uv add verwenden.

So installieren Sie UV

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

Erstellen Sie einen Projektordner

Wenn Sie sich für die Verwendung von pip entschieden haben, müssen Sie einen Projektordner erstellen.

uv init phidata-ollama

Abhängigkeiten installieren

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

In diesem Artikel werden wir versuchen, 5 KI-Agenten mit Phidata und Ollama zu erstellen.
Hinweis: Bevor Sie beginnen, stellen Sie sicher, dass Ihr Ollama-Server läuft, indem Sie „Ollama Serve“ ausführen.

Erstellen Sie einen Web-Suchagenten

Der erste Agent, den wir erstellen werden, ist ein Websuchagent, der die Suchmaschine DuckDuckGo verwendet.

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)

Ausgabe:

┏━ 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.                                ┃
┃                                                                         ┃
┗━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━┛

Erstellen Sie einen Finanzagenten

Der zweite Agent, den wir erstellen werden, ist ein Finanzagent, der Yfinance-Tools verwenden wird.

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)

Ausgabe:

┏━ 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.                                               ┃
┃                                                                         ┃
┗━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━┛

Erstellen Sie ein Agententeam

Der dritte Agent, den wir erstellen werden, ist ein Agententeam, das die Suchmaschine DuckDuckGo und die YFinance-Tools verwendet.

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)

Erstellen Sie einen Inferenzagenten

Der vierte Agent, den wir erstellen werden, ist ein Inferenzagent, der eine Aufgabe verwendet.

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)

Ausgabe:

┏━ 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]

Erstellen Sie einen RAG-Agenten

Der fünfte Agent, den wir erstellen werden, ist ein RAG-Agent, der eine PDF-Wissensdatenbank und eine LanceDB-Vektordatenbank verwendet.

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)

Ausgabe:

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                                                      ┃
┃                                                                         ┃
┗━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━┛

Abschluss

In diesem Artikel haben wir untersucht, wie man mithilfe von Phidata und dem lokalen LLM von Ollama KI-Agenten für die Websuche, Finanzanalyse, Argumentation und abrufgestützte Generierung erstellt.

Das obige ist der detaillierte Inhalt vonAufbau I Agenten mit Phidata und Ollama. Für weitere Informationen folgen Sie bitte anderen verwandten Artikeln auf der PHP chinesischen Website!

Stellungnahme
Der Inhalt dieses Artikels wird freiwillig von Internetnutzern beigesteuert und das Urheberrecht liegt beim ursprünglichen Autor. Diese Website übernimmt keine entsprechende rechtliche Verantwortung. Wenn Sie Inhalte finden, bei denen der Verdacht eines Plagiats oder einer Rechtsverletzung besteht, wenden Sie sich bitte an admin@php.cn
Pythons Hybridansatz: Zusammenstellung und Interpretation kombiniertPythons Hybridansatz: Zusammenstellung und Interpretation kombiniertMay 08, 2025 am 12:16 AM

Pythonusesahybridapproach, kombinierte CompilationTobyteCodeAnDinterpretation.1) codiscompiledtoplatform-unintenpendentBytecode.2) BytecodeIsinterpretedBythepythonvirtualMachine, EnhancingEfficiency und Portablabilität.

Erfahren Sie die Unterschiede zwischen Pythons 'für' und 'while the' LoopsErfahren Sie die Unterschiede zwischen Pythons 'für' und 'while the' LoopsMay 08, 2025 am 12:11 AM

Die Keedifferzences -zwischen Pythons "für" und "während" Loopsare: 1) "für" LoopsareideAlForiteratingOvercesorknownowniterations, während 2) "LoopsarebetterForContiningUtilAconditionismethoutnredefineditInations.un

Python verkettet Listen mit DuplikatenPython verkettet Listen mit DuplikatenMay 08, 2025 am 12:09 AM

In Python können Sie Listen anschließen und doppelte Elemente mit einer Vielzahl von Methoden verwalten: 1) Verwenden von Operatoren oder erweitert (), um alle doppelten Elemente beizubehalten; 2) Konvertieren in Sets und kehren Sie dann zu Listen zurück, um alle doppelten Elemente zu entfernen. Die ursprüngliche Bestellung geht jedoch verloren. 3) Verwenden Sie Schleifen oder listen Sie Verständnisse auf, um Sätze zu kombinieren, um doppelte Elemente zu entfernen und die ursprüngliche Reihenfolge zu verwalten.

Python List -Verkettungsleistung: GeschwindigkeitsvergleichPython List -Verkettungsleistung: GeschwindigkeitsvergleichMay 08, 2025 am 12:09 AM

THESTESTMETHODFORLISTCONCATENATIONINPYTHONDSONLISTSIZE: 1) ForsmallLists, The Operatoriseffiction.2) Forlargerlists, list.extend () orlistCompretInsisfaster, WithEttend () MORMOREMEIMIENTIENTIENTYMODIFICIENTLISTLISTERSIN-SPACE.

Wie setzen Sie Elemente in eine Python -Liste ein?Wie setzen Sie Elemente in eine Python -Liste ein?May 08, 2025 am 12:07 AM

ToInsertElementsIntoapherthonList, useAppend () toaddtotheend, insert () foraspecificposition und fortend () formulpulpulements.1) useeAppend () Foraddingsingleiitemstotheend.2) useInsert () toaddataspecificIndex, zwarsititithulsForlargerists

Sind Python -Listen dynamische Arrays oder verknüpfte Listen unter der Haube?Sind Python -Listen dynamische Arrays oder verknüpfte Listen unter der Haube?May 07, 2025 am 12:16 AM

PythonlistsarEmplementedasdynamicArrays, Notlinkedlists.1) Sie haben incontuituousMemoryblocks, die ausgelöst werden, wobei die Auswirkungen auf die Erfüllung von Zeitungen/Deletionsbutionen, die in Verbindung gebracht wurden

Wie entfernen Sie Elemente aus einer Python -Liste?Wie entfernen Sie Elemente aus einer Python -Liste?May 07, 2025 am 12:15 AM

PythonoffersfourmainMethodstoremoveLements Fromalist: 1) Entfernen (Wert) removesthefirstoccurceofavalue, 2) Pop (index) removesandreturnsanelementataspecifiedIndex, 3) DelstatementRemovesElementsbyIntexors und 4) clear () removesallitems

Was sollten Sie überprüfen, wenn Sie einen Fehler 'Erlaubnis abgelehnt' erhalten, wenn Sie versuchen, ein Skript auszuführen?Was sollten Sie überprüfen, wenn Sie einen Fehler 'Erlaubnis abgelehnt' erhalten, wenn Sie versuchen, ein Skript auszuführen?May 07, 2025 am 12:12 AM

ToreSolvea "Berechtigte" FehlerwherunningAscript, folgen von THESESTEPS: 1) checkandadjustThescript'SPERMISSIONSCHMOD XMYSCRIPT.SHTOMAKEPEXEx.

See all articles

Heiße KI -Werkzeuge

Undresser.AI Undress

Undresser.AI Undress

KI-gestützte App zum Erstellen realistischer Aktfotos

AI Clothes Remover

AI Clothes Remover

Online-KI-Tool zum Entfernen von Kleidung aus Fotos.

Undress AI Tool

Undress AI Tool

Ausziehbilder kostenlos

Clothoff.io

Clothoff.io

KI-Kleiderentferner

Video Face Swap

Video Face Swap

Tauschen Sie Gesichter in jedem Video mühelos mit unserem völlig kostenlosen KI-Gesichtstausch-Tool aus!

Heiße Werkzeuge

MinGW – Minimalistisches GNU für Windows

MinGW – Minimalistisches GNU für Windows

Dieses Projekt wird derzeit auf osdn.net/projects/mingw migriert. Sie können uns dort weiterhin folgen. MinGW: Eine native Windows-Portierung der GNU Compiler Collection (GCC), frei verteilbare Importbibliotheken und Header-Dateien zum Erstellen nativer Windows-Anwendungen, einschließlich Erweiterungen der MSVC-Laufzeit zur Unterstützung der C99-Funktionalität. Die gesamte MinGW-Software kann auf 64-Bit-Windows-Plattformen ausgeführt werden.

Senden Sie Studio 13.0.1

Senden Sie Studio 13.0.1

Leistungsstarke integrierte PHP-Entwicklungsumgebung

Sicherer Prüfungsbrowser

Sicherer Prüfungsbrowser

Safe Exam Browser ist eine sichere Browserumgebung für die sichere Teilnahme an Online-Prüfungen. Diese Software verwandelt jeden Computer in einen sicheren Arbeitsplatz. Es kontrolliert den Zugriff auf alle Dienstprogramme und verhindert, dass Schüler nicht autorisierte Ressourcen nutzen.

Notepad++7.3.1

Notepad++7.3.1

Einfach zu bedienender und kostenloser Code-Editor

VSCode Windows 64-Bit-Download

VSCode Windows 64-Bit-Download

Ein kostenloser und leistungsstarker IDE-Editor von Microsoft