Ollama를 사용하면 오픈 소스 모델을 로컬로 실행하고 에이전트 프레임워크와 함께 사용할 수 있습니다. 온-프레미스 데이터를 유지해야 하는 개발, 테스트 및 시나리오에 적합합니다.
사전 요구 사항
- Ollama를 설치하고 시작합니다.
- 와 같은
ollama pull llama3.2모델을 다운로드합니다.
설치
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."));
사전 요구 사항
예제를 실행하기 전에 모델을 다운로드하여 Ollama 가 설치되고 로컬로 실행되고 있는지 확인합니다.
ollama pull llama3.2
비고
모든 모델이 함수 호출을 지원하지는 않습니다. 도구 사용의 경우 시도하거나 llama3.2.qwen3:4b
설치
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 및 Ollama 호환 엔드포인트를 가리키는 OpenAIChatClient)는 로컬로 호출된 도구를 지원합니다. Ollama는 로컬 모델 런타임이므로 호스트된 도구 형식이 없습니다.
| Tool | 상태 | Notes |
|---|---|---|
| 함수 도구 | ✅ | 표준 Python 호출 가능 객체 또는 @ai_function. 선택한 모델이 실제로 호출할 수 있는지 여부는 모델 자체에 따라 달라집니다. |
| 도구 승인 | ✅ | 프레임워크의 함수 호출 채팅 클라이언트에서 제공합니다. 함수 도구 호출과 함께 작동합니다. |
| 코드 해석기 | ❌ | 호스트된 코드 인터프리터가 없습니다. |
| 파일 검색 | ❌ | 호스트된 파일 검색이 없습니다. |
| 웹 검색 | ❌ | 호스트된 웹 검색이 없습니다. |
| 호스트된 MCP 도구 | ❌ | Ollama는 호스트된 MCP를 노출하지 않습니다. |
| 로컬 MCP 도구 | ✅ | 프로세스에서 실행되며 모든 채팅 클라이언트에서 작동합니다. |
함수 도구
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 리포지토리 를 참조하세요.