Condividi tramite


Ollama

Ollama consente di eseguire modelli open source in locale e di usarli con Agent Framework. Questo è ideale per lo sviluppo, il test e gli scenari in cui è necessario mantenere i dati in locale.

L'esempio seguente illustra come creare un agente usando Ollama:

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?"));

Prerequisiti

Verificare che Ollama sia installato ed eseguito localmente con un modello scaricato prima di eseguire esempi:

ollama pull llama3.2

Annotazioni

Non tutti i modelli supportano la chiamata di funzione. Per l'utilizzo degli strumenti, provare llama3.2 o qwen3:4b.

Installazione

pip install agent-framework-ollama --pre

Configurazione

OLLAMA_MODEL_ID="llama3.2"

Il client nativo si connette a per http://localhost:11434 impostazione predefinita. È possibile eseguire l'override di questa operazione passando host al client.

Creare agenti Ollama

OllamaChatClient offre l'integrazione nativa di Ollama con supporto completo per gli strumenti e lo streaming delle funzioni.

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())

Strumenti per le funzioni

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())

Trasmissione in diretta

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()

Passaggi successivi