Build a Local AI Agent with Semantic Kernel and Ollama
What you will build
Microsoft's Semantic Kernel is an open-source SDK for building AI agents in Python, C#, and Java. A kernel holds your model service, plugins wrap ordinary functions as tools the model can call, and an agent runs the loop that ties them together. Pair it with Ollama and the same agent runs entirely on your own machine, on a local model, with no cloud API key and no data leaving your laptop.
In this tutorial you will build a small notes agent: it reads a folder of plain-text notes, answers questions about them, and keeps the conversation going across turns. The whole thing is about 60 lines of Python. Every command and code snippet below was tested against semantic-kernel 1.45.0, the latest release at the time of writing.
One honest note before you start: Microsoft now positions Microsoft Agent Framework as the successor to Semantic Kernel, and it reached 1.0 in April 2026. Semantic Kernel 1.x is still supported — critical bug fixes and security fixes for at least a year after MAF's 1.0 release — so it remains a solid choice for a local project, and the patterns here (kernel, plugins, function calling) carry over to the new framework.
Source: Microsoft Learn — Semantic Kernel overview diagram.
Prerequisites
- Python 3.10 or newer
- Ollama installed and running
- A model that supports tool calling. This guide uses
qwen3:8b— Qwen 3 is on Ollama's own list of tool-capable models, along with Llama 3.1 and Llama 4. Smaller models often ignore tools or call them with broken arguments, so pick a model that actually supports them.
Step 1: Pull a tool-capable model
ollama pull qwen3:8b
ollama list
Check that Ollama is answering on its default port:
curl http://localhost:11434/api/tags
If that fails with a connection error, start Ollama first (ollama serve on Linux, or launch the app on macOS and Windows) and try again.
Step 2: Install Semantic Kernel
Create a virtual environment and install the package with the Ollama extra, which pulls in the Ollama Python client:
python -m venv .venv
source .venv/bin/activate
pip install "semantic-kernel[ollama]==1.45.0"
On Windows, activate with .venv\Scripts\activate instead of the source line.
Step 3: Give the agent a tool
Semantic Kernel calls tools "plugins": a class whose methods are decorated with @kernel_function. Type hints and descriptions become the schema the model sees, so write them as if you were explaining the function to a colleague. This plugin exposes two tools over a folder of notes:
from pathlib import Path
from typing import Annotated
from semantic_kernel.functions import kernel_function
NOTES_DIR = Path("notes")
NOTES_DIR.mkdir(exist_ok=True)
class NotesPlugin:
"""Tools for reading plain-text notes from the notes folder."""
@kernel_function(description="List the titles of all saved notes.")
def list_notes(self) -> Annotated[str, "Note titles, one per line."]:
files = sorted(NOTES_DIR.glob("*.txt"))
if not files:
return "No notes saved yet."
return "\n".join(f.stem for f in files)
@kernel_function(description="Read the full text of one note by title.")
def read_note(
self, title: Annotated[str, "The note title, without the .txt extension."]
) -> Annotated[str, "The note text, or an error message."]:
path = NOTES_DIR / f"{title}.txt"
if not path.exists():
return f"No note titled '{title}'."
return path.read_text(encoding="utf-8")
Add a couple of notes so the agent has something to work with:
mkdir -p notes
echo "Buy oat milk, coffee beans, and rye bread." > notes/shopping.txt
echo "Idea: a local-first reading list app with offline search." > notes/ideas.txt
Step 4: Connect Ollama and turn on function calling
The Ollama connector is OllamaChatCompletion. It defaults to http://127.0.0.1:11434, so you only need to pass the host when Ollama runs elsewhere. Function calling is switched on through execution settings:
import asyncio
from semantic_kernel import Kernel
from semantic_kernel.connectors.ai.function_choice_behavior import FunctionChoiceBehavior
from semantic_kernel.connectors.ai.ollama import OllamaChatCompletion
from semantic_kernel.connectors.ai.ollama.ollama_prompt_execution_settings import (
OllamaChatPromptExecutionSettings,
)
from semantic_kernel.functions import KernelArguments
service = OllamaChatCompletion(ai_model_id="qwen3:8b", host="http://localhost:11434")
settings = OllamaChatPromptExecutionSettings(
function_choice_behavior=FunctionChoiceBehavior.Auto()
)
FunctionChoiceBehavior.Auto() lets the model decide when to call a tool and when to answer directly. Without it, the model will describe your tools instead of using them.
Step 5: Build the agent and chat with it
ChatCompletionAgent takes the service, a name, instructions, and your plugins. A ChatHistory object carries the conversation across turns — add each user message and each reply to it, and pass it back on every call:
Source: Microsoft Semantic Kernel blog — how an agent request flows through plugins.
from semantic_kernel.agents import ChatCompletionAgent
from semantic_kernel.contents import ChatHistory
async def main():
agent = ChatCompletionAgent(
service=service,
name="NotesAgent",
instructions=(
"You are a helpful assistant for personal notes. "
"Use the notes tools to answer questions about the notes. "
"If a note does not exist, say so instead of guessing."
),
plugins=[NotesPlugin()],
arguments=KernelArguments(settings=settings),
)
history = ChatHistory()
print("Notes agent ready. Type 'exit' to quit.")
while True:
user_input = input("You: ")
if user_input.strip().lower() in {"exit", "quit"}:
break
history.add_user_message(user_input)
response = await agent.get_response(history)
print(f"Agent: {response.content}")
history.add_assistant_message(response.content)
asyncio.run(main())
Save this as agent.py and run it:
python agent.py
Try asking "What notes do I have?" and then "What is on my shopping list?" The first question should trigger list_notes, the second read_note with the title shopping. The model only writes the order to call a tool — your plugin code does the actual reading, and the result goes back to the model before it answers.
Troubleshooting
- The agent answers from memory instead of calling a tool. Check two things: the model (use a tool-capable one such as
qwen3:8borllama3.1:8b) and the settings (FunctionChoiceBehavior.Auto()must be passed througharguments). - Connection refused on port 11434. Ollama is not running. Run
ollama serveor start the Ollama app, then re-check withcurl http://localhost:11434/api/tags. - The first reply is slow. Ollama loads the model into memory on the first request. Later replies are much faster, and the model unloads after a period of inactivity.
ModuleNotFoundError: No module named 'semantic_kernel'. The virtual environment is not active, or the install went to a different Python. Re-run thesource .venv/bin/activateline and the pip install in the same terminal.
Where to go from here
The pattern scales further than this demo: add a plugin that writes notes, one that searches the web, or one that runs shell commands — keeping each tool small and explicit, since the model decides when to call it. If you want a comparison point, the same stack works with other frameworks too: our LangGraph tutorial builds a similar local agent with a graph-based loop, Goose with Ollama gives you a ready-made agent you can run without writing code, and OpenCode with Ollama turns the same idea into a coding assistant. And when you are ready for a bigger project, the migration guide to Microsoft Agent Framework covers moving this code to the new framework.


Comments
Post a Comment