Ollama

Ollama vous permet d’exécuter des modèles open source localement et de les utiliser avec Agent Framework. Cela est idéal pour le développement, les tests et les scénarios dans lesquels vous devez conserver des données locales.

Prerequisites

  • Installez et démarrez Ollama.
  • Téléchargez un modèle, tel que ollama pull llama3.2.

Installation

dotnet add package OllamaSharp
dotnet add package Microsoft.Agents.AI --prerelease

Configuration

OLLAMA_ENDPOINT="http://localhost:11434"
OLLAMA_MODEL_NAME="llama3.2"

Créer un agent Ollama

using Microsoft.Agents.AI;
using Microsoft.Extensions.AI;
using OllamaSharp;

var endpoint = Environment.GetEnvironmentVariable("OLLAMA_ENDPOINT") ?? throw new InvalidOperationException("OLLAMA_ENDPOINT is not set.");
var modelName = Environment.GetEnvironmentVariable("OLLAMA_MODEL_NAME") ?? throw new InvalidOperationException("OLLAMA_MODEL_NAME is not set.");

// Get a chat client for Ollama and use it to construct an AIAgent.
AIAgent agent = new OllamaApiClient(new Uri(endpoint), modelName)
    .AsAIAgent(instructions: "You are good at telling jokes.", name: "Joker");

// Invoke the agent and output the text result.
Console.WriteLine(await agent.RunAsync("Tell me a joke about a pirate."));

Prerequisites

Vérifiez que Ollama est installé et exécuté localement avec un modèle téléchargé avant d’exécuter des exemples :

ollama pull llama3.2

Note

Tous les modèles ne prennent pas en charge l’appel de fonction. Pour l’utilisation de l’outil, essayez llama3.2 ou qwen3:4b.

Installation

pip install agent-framework-ollama --pre

Configuration

OLLAMA_MODEL="llama3.2"

Le client natif se connecte http://localhost:11434 par défaut. Remplacez-le par la variable d’environnement OLLAMA_HOST ou l’argument constructeur host .

Créer des agents Ollama

OllamaChatClient fournit une intégration native de Ollama avec une prise en charge complète des outils de fonction et du streaming.

import asyncio
from agent_framework import Agent
from agent_framework.ollama import OllamaChatClient

async def main():
    agent = Agent(
        client=OllamaChatClient(),
        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())

Tools

Les clients Ollama Python (OllamaChatClient et OpenAIChatClient point de terminaison compatible avec Ollama) prennent en charge les outils appelés localement. Les types d’outils hébergés n’existent pas, car Ollama est un runtime de modèle local.

Tool Status Remarques
Outils de fonction Appels standard Python ou @ai_function. Si le modèle sélectionné peut réellement les appeler dépend du modèle lui-même.
Approbation de l’outil Fourni par le client de chat du framework permettant d’invoquer des fonctions ; fonctionne avec tout appel à un outil-fonction.
Interpréteur de code Aucun interpréteur de code hébergé.
Recherche de fichiers Aucune recherche de fichier hébergée.
Recherche web Aucune recherche web hébergée.
Outils MCP hébergés Ollama n’expose pas mcP hébergé.
Outils MCP locaux S’exécute dans votre processus et fonctionne avec n’importe quel client de conversation.

Outils de fonction

import asyncio
from datetime import datetime
from agent_framework import Agent
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 = Agent(
        client=OllamaChatClient(),
        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())

Diffusion en continu

from agent_framework import Agent
from agent_framework.ollama import OllamaChatClient

async def streaming_example():
    agent = Agent(
        client=OllamaChatClient(),
        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()

Note

La prise en charge de Go pour cette fonctionnalité arrivera bientôt. Consultez le référentiel Agent Framework Go pour connaître l’état le plus récent.

Étapes suivantes