Ollama 允许在本地运行开源模型,并将其与 Agent Framework 配合使用。 这非常适合用于在本地保留数据的开发、测试和方案。
Warning
支持时,将模型或嵌入输出和模型生成的工具调用视为不受信任的应用程序输入。 在代码执行副作用或呈现内容之前对其进行验证。 如果配置自定义终结点,请验证是否信任其 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 代理
Prerequisites
在运行任何示例之前,请确保 Ollama 已安装并在本地运行并运行已下载的模型:
ollama pull llama3.2
注释
并非所有模型都支持函数调用。 对于工具用法,请尝试 llama3.2 或 qwen3:4b尝试。
Installation
Configuration
OLLAMA_MODEL="llama3.2"
默认情况下,本机客户端连接到 http://localhost:11434 该客户端。 使用 OLLAMA_HOST 环境变量或 host 构造函数参数重写它。
创建 Ollama 代理
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 是本地模型运行时。
| 工具 | 地位 | 注释 |
|---|---|---|
| 函数工具 | ✅ | 标准 Python 可调用对象或 @ai_function。 所选模型是否可以实际调用它们取决于模型本身。 |
| 工具审批 | ✅ | 由框架中支持函数调用的聊天客户端提供;可与任何函数工具调用配合使用。 |
| 代码解释器 | ❌ | 没有托管的代码解释器。 |
| 文件搜索 | ❌ | 没有托管的文件搜索。 |
| Web 搜索 | ❌ | 没有托管的 Web 搜索。 |
| 托管 MCP 工具 | ❌ | Ollama 不公开托管的 MCP。 |
| 本地 MCP 工具 | ✅ | 在进程中运行,并适用于任何聊天客户端。 |
对于本机 OllamaChatClient, tool_choice 支持 auto 和 none。
默认值并 auto 发送配置的工具,同时 none 从请求中省略它们。 包括allowed_tools引发ChatClientInvalidRequestException的required模式和选项,因为 Ollama 无法强制执行它们。
函数工具
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 存储库 。