Ollama

Ollama 允許你在本地執行開源模型,並與 Agent Framework 一起使用。 這對於開發、測試以及需要將資料儲存在本地的情境來說非常理想。

警告

將模型或嵌入輸出,以及支援時由模型產生的工具呼叫,視為不可信的應用程式輸入。 在程式碼產生副作用或渲染內容之前,先驗證它們。 如果你設定自訂端點,請確認你信任它的 URL 和運算子。

Prerequisites

  • 安裝並啟動 Ollama。
  • 下載一個模型,例如 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"

創建一位 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

在執行任何範例前,請確保 Ollama 已安裝並本地運行,並下載了模型:

ollama pull llama3.2

備註

並非所有模型都支援函式呼叫。 工具使用時,試試 llama3.2 或 qwen3:4b。

Installation

pip install agent-framework-ollama --pre

Configuration

OLLAMA_MODEL="llama3.2"

原生客戶端預設連線到http://localhost:11434 用 OLLAMA_HOST 環境變數或 host 建構子參數覆蓋它。

創造奧拉瑪特工

OllamaChatClient 提供原生 Ollama 整合,並完整支援函式工具與串流。

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

Python Ollama 用戶端(OllamaChatClient 和 OpenAIChatClient,指向 Ollama 相容端點)支援本地調用工具。 由於 Ollama 是本地模型執行環境,故不存在託管工具類型。

Tool 現況 註釋
函式工具 ✅ 標準 Python 可呼叫物件或 @ai_function。 所選模型是否能實際呼叫它們,取決於模型本身。
工具核准 ✅ 由框架的函式呼叫聊天客戶端提供;適用於任何函式工具呼叫。
程式碼解譯器 ❌ 沒有託管的程式碼直譯器。
檔案搜尋 ❌ 沒有託管檔案搜尋。
網路搜尋 ❌ 沒有託管的網路搜尋。
託管 MCP 工具 ❌ Ollama 不會暴露託管的 MCP。
本地 MCP 工具 ✅ 它會直接運行在你的流程裡,並且能搭配任何聊天客戶端使用。

對於原生 OllamaChatClient、 tool_choice 支援 auto 和 none。 預設 和 auto send 已設定的工具,而 none 在請求中省略這些工具。 required包含加注ChatClientInvalidRequestException的模式和選項allowed_tools,因為奧拉瑪無法強制執行。

功能工具

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

Streaming

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

備註

Go 對此功能的支援即將推出。 最新狀態請參閱 Agent Framework Go 倉庫 。

下一步