Freigeben über


Ollama

Mit Ollama können Sie Open-Source-Modelle lokal ausführen und mit Agent Framework verwenden. Dies eignet sich ideal für Entwicklung, Tests und Szenarien, in denen Sie Daten lokal aufbewahren müssen.

Das folgende Beispiel zeigt, wie Sie einen Agent mit Ollama erstellen:

using System;
using Microsoft.Agents.AI;
using Microsoft.Extensions.AI;

// Create an Ollama agent using Microsoft.Extensions.AI.Ollama
// Requires: dotnet add package Microsoft.Extensions.AI.Ollama --prerelease
var chatClient = new OllamaChatClient(
    new Uri("http://localhost:11434"),
    modelId: "llama3.2");

AIAgent agent = chatClient.AsAIAgent(
    instructions: "You are a helpful assistant running locally via Ollama.");

Console.WriteLine(await agent.RunAsync("What is the largest city in France?"));

Voraussetzungen

Stellen Sie sicher, dass Ollama lokal mit einem heruntergeladenen Modell installiert und ausgeführt wird, bevor Sie Beispiele ausführen:

ollama pull llama3.2

Hinweis

Nicht alle Modelle unterstützen Funktionsaufrufe. Für die Toolverwendung versuchen llama3.2 oder qwen3:4b.

Installation

pip install agent-framework-ollama --pre

Konfiguration

OLLAMA_MODEL_ID="llama3.2"

Der native Client stellt standardmäßig eine Verbindung mit dem systemeigenen Client bereit http://localhost:11434 . Sie können dies überschreiben, indem Sie an den Client übergeben host .

Erstellen von Ollama Agents

OllamaChatClient bietet native Ollama-Integration mit vollständiger Unterstützung für Funktionstools und Streaming.

import asyncio
from agent_framework.ollama import OllamaChatClient

async def main():
    agent = OllamaChatClient().as_agent(
        name="HelpfulAssistant",
        instructions="You are a helpful assistant running locally via Ollama.",
    )
    result = await agent.run("What is the largest city in France?")
    print(result)

asyncio.run(main())

Funktionstools

import asyncio
from datetime import datetime
from agent_framework.ollama import OllamaChatClient

def get_time(location: str) -> str:
    """Get the current time."""
    return f"The current time in {location} is {datetime.now().strftime('%I:%M %p')}."

async def main():
    agent = OllamaChatClient().as_agent(
        name="TimeAgent",
        instructions="You are a helpful time agent.",
        tools=get_time,
    )
    result = await agent.run("What time is it in Seattle?")
    print(result)

asyncio.run(main())

Streamen

async def streaming_example():
    agent = OllamaChatClient().as_agent(
        instructions="You are a helpful assistant.",
    )
    print("Agent: ", end="", flush=True)
    async for chunk in agent.run("Tell me about Python.", stream=True):
        if chunk.text:
            print(chunk.text, end="", flush=True)
    print()

Nächste Schritte