Semantic Kernel Function Calling with a Local LLM: Fixes
Semantic Kernel function calling with a local LLM fails for three usual reasons: the model or its chat template lacks tool support, auto-invocation is not enabled, or the plugin sits on a different Kernel than the one passed to the call.
- Test the server with a raw curl request containing a tools array first: if no tool_calls come back, the model or server is the problem, not Semantic Kernel.
- Set FunctionChoiceBehavior = FunctionChoiceBehavior.Auto() in the execution settings and pass kernel: kernel into GetChatMessageContentAsync.
- Use a tool-trained model such as Llama 3.1 8B Instruct, Qwen2.5 or Qwen3 Instruct, Mistral or Hermes 3, and confirm the Ollama 'tools' capability.
- Add an IFunctionInvocationFilter to prove whether functions run, and try non-streaming and a context window of 8k or more before anything else.
- Describe every plugin method and parameter with [KernelFunction] and [Description], and keep parameter types simple.
Why does Semantic Kernel function calling with a local LLM never call my function?
Seeing the plugin schema in the outgoing request only proves Semantic Kernel did its half. Function calling is a contract between three layers: your code (which sends a tools array and executes returned calls), the server (which must accept tools and render them into the prompt), and the model (which must be trained to emit a structured call). A failure in any layer looks identical: the model answers in plain prose.
There are three common root causes. First, the model or its chat template has no tool support, so the schema is ignored or pasted as text. Second, auto-invocation is not enabled, or the plugin is on a different Kernel. Third, the server or settings interfere: streaming, a tiny context window, or high temperature.
Separate them in this order: curl the server directly, then check the C# settings, then check the Kernel wiring. That order stops you from debugging C# when the model was never capable.
How do I test tool calling with curl before touching C#?
Send an OpenAI-style request with a tools array straight to the server. Use port 1234 for LM Studio or 11434 for Ollama (its OpenAI-compatible path is /v1). A capable model returns a message with tool_calls and empty content; an incapable one returns normal content.
curl http://localhost:11434/v1/chat/completions \
-H "Content-Type: application/json" \
-d '{
"model": "llama3.1:8b",
"temperature": 0,
"messages": [{"role":"user","content":"Turn on the kitchen light."}],
"tools": [{
"type":"function",
"function":{
"name":"set_light",
"description":"Turn a light on or off by room name",
"parameters":{"type":"object",
"properties":{"room":{"type":"string"},"on":{"type":"boolean"}},
"required":["room","on"]}}}]
}'Which local models support tool calling reliably?
Tool calling needs both training on call-formatted data and a chat template that renders the tools and parses the output. Ollama and LM Studio only enable it when the template supports it, which is why a model can be fine in chat and silent with tools.
Small or old models are the usual culprits. Phi-3-mini, command-r-v01, and Llama 3.2 3B at aggressive quantization (Q2, Q3) often return text even with tools present.
| Model family | Tool use | Notes |
|---|---|---|
| Llama 3.1 Instruct 8B or larger | Good | Safe first choice; Q4_K_M or higher |
| Llama 3.2 3B Instruct | Fair | Works at Q6 or Q8; weak at low quantization, may skip calls |
| Qwen2.5 Instruct 7B+ | Good | Strong at argument extraction |
| Qwen3 (non-thinking or tool-tagged builds) | Good | Check your build's template; thinking output can clutter replies |
| Mistral 7B Instruct (v0.3) / Mistral Nemo | Good | Needs a template with tool tokens |
| Hermes 2 Pro / Hermes 3 | Good | Trained specifically for tool use |
| Phi-3-mini | Poor | Often answers in prose |
| command-r-v01 | Poor | Frequently ignores tools |
How do I set up auto-invocation and the kernel correctly?
Two settings matter. FunctionChoiceBehavior.Auto() tells Semantic Kernel to advertise functions and invoke the returned calls itself. The older ToolCallBehavior.AutoInvokeKernelFunctions is obsolete, so do not copy it from old samples.
The second is the Kernel. Plugins live on the Kernel, so you must pass that exact instance into the call. If you fetch IChatCompletionService and call it without kernel: kernel, no tools are sent for execution and nothing is invoked. The same happens if you register plugins on one Kernel and pass another, which is common when builders are created in two places.
Below is a minimal Program.cs for both servers, plus the plugin.
// Program.cs (C#)
using System.ComponentModel;
using Microsoft.SemanticKernel;
using Microsoft.SemanticKernel.ChatCompletion;
using Microsoft.SemanticKernel.Connectors.OpenAI;
var builder = Kernel.CreateBuilder();
// LM Studio (OpenAI-compatible)
builder.AddOpenAIChatCompletion(
modelId: "qwen2.5-7b-instruct",
apiKey: "lm-studio", // dummy value
endpoint: new Uri("http://localhost:1234/v1"));
// Ollama alternative (Microsoft.SemanticKernel.Connectors.Ollama, prerelease):
// builder.AddOllamaChatCompletion("llama3.1:8b", new Uri("http://localhost:11434"));
builder.Plugins.AddFromType<LightsPlugin>("Lights");
var kernel = builder.Build();
var chat = kernel.GetRequiredService<IChatCompletionService>();
var settings = new OpenAIPromptExecutionSettings
{
FunctionChoiceBehavior = FunctionChoiceBehavior.Auto(),
Temperature = 0.1
};
var history = new ChatHistory("You are a home assistant. Always use the Lights tools to check or change lights; never guess their state.");
history.AddUserMessage("Turn on the kitchen light.");
var reply = await chat.GetChatMessageContentAsync(history, settings, kernel: kernel);
Console.WriteLine(reply.Content);
public class LightsPlugin
{
[KernelFunction("set_light")]
[Description("Turns a light on or off in the named room.")]
public async Task<string> SetLightAsync(
[Description("Room name, for example kitchen")] string room,
[Description("true to turn on, false to turn off")] bool on)
{
await Task.Delay(10);
return $"{room} light is now {(on ? "on" : "off")}";
}
[KernelFunction("get_lights")]
[Description("Lists all rooms and whether their light is on.")]
public string GetLights() => "kitchen: off, bedroom: off";
}How do I use ChatCompletionAgent and KernelPluginFactory with Ollama?
A working pattern for agents is to build the plugin explicitly, add it to the agent's own Kernel, and set the behavior through Arguments. Here the agent reads function choice from KernelArguments, so settings on a different object are not applied.
On the factory question: Plugins.AddFromType<T>() and KernelPluginFactory.CreateFromType<T>() build the same kind of plugin. CreateFromType returns the plugin so you can add it to any Kernel; CreateFromObject does the same for an instance with state or injected dependencies. Use AddFromType for the simple case and the factory when you build kernels separately, which is exactly where the wrong-Kernel bug appears.
// C#
var kb = Kernel.CreateBuilder();
kb.AddOllamaChatCompletion("llama3.1:8b", new Uri("http://localhost:11434"));
var agentKernel = kb.Build();
agentKernel.Plugins.Add(KernelPluginFactory.CreateFromType<LightsPlugin>("Lights"));
// or: KernelPluginFactory.CreateFromObject(new LightsPlugin(), "Lights")
var agent = new ChatCompletionAgent
{
Name = "HomeAgent",
Instructions = "Use the Lights tools to answer. Do not guess.",
Kernel = agentKernel,
Arguments = new KernelArguments(new PromptExecutionSettings
{
FunctionChoiceBehavior = FunctionChoiceBehavior.Auto()
})
};
await foreach (var item in agent.InvokeAsync("Turn on the kitchen light"))
Console.WriteLine(item.Message.Content);How do I debug whether functions are actually being called?
Add an IFunctionInvocationFilter. If it logs nothing, the model never returned a tool call; if it logs and the answer is still odd, the problem is your function output.
To see raw traffic, put a DelegatingHandler on the HttpClient you pass to the connector, and log request and response bodies. In the response, look for choices[0].message.tool_calls versus content.
// C#
public class LogFilter : IFunctionInvocationFilter
{
public async Task OnFunctionInvocationAsync(
FunctionInvocationContext ctx, Func<FunctionInvocationContext, Task> next)
{
Console.WriteLine($"CALL {ctx.Function.PluginName}.{ctx.Function.Name} args={string.Join(",", ctx.Arguments)}");
await next(ctx);
Console.WriteLine($"RESULT {ctx.Result}");
}
}
kernel.FunctionInvocationFilters.Add(new LogFilter()); What other settings stop local models from calling tools?
Streaming is a frequent hidden cause: some local servers or versions do not emit tool calls in streamed responses. Test with GetChatMessageContentAsync (non-streaming) first, then add streaming once it works.
Context size matters too. Ollama defaults to a small window (often 2k to 4k depending on version), and tool schemas plus history consume it. Set num_ctx to 8192 or more, and in LM Studio raise the context length when loading the model. Keep temperature at 0 to 0.3, since high values make argument formatting unreliable.
Finally, small models respond to explicit prompting. Say 'use the set_light tool' in the system prompt, and avoid vague instructions like 'be helpful'.
| Symptom | Likely cause | Fix |
|---|---|---|
| curl returns plain text with tools | Model or template lacks tool support | Switch to Llama 3.1 8B, Qwen2.5, Hermes 3; check 'ollama show' |
| Schema in request, no filter logs | Auto-invoke not enabled | Set FunctionChoiceBehavior.Auto() |
| No tools in request at all | Kernel not passed or wrong Kernel | Pass kernel: kernel; register plugin on that instance |
| Agent ignores plugin | Settings not in Arguments | Use Arguments = new KernelArguments(settings) |
| Works non-streaming only | Server lacks streaming tool calls | Use non-streaming |
| Malformed or missing arguments | Low quantization, high temperature | Use Q4_K_M or higher, temperature 0 to 0.3 |
| Answers generically, long prompts | Context too small | Set num_ctx or context length to 8k+ |
| Model never picks the right function | Vague names or descriptions | Clear names, [Description] on method and parameters |
Common questions
Does Semantic Kernel function calling work with Ollama?
Yes, with a tool-capable model such as Llama 3.1 or Qwen2.5. Use the Ollama connector with AddOllamaChatCompletion, or the OpenAI-compatible /v1 endpoint, and confirm the model lists tools under 'ollama show'.
Why is my LM Studio plugin not invoked?
Usually the loaded model is not tool-trained or the LM Studio version does not honor the tools parameter. Test with curl, load a model with the tool-use badge, and make sure you passed kernel: kernel with Auto() enabled.
What replaced ToolCallBehavior.AutoInvokeKernelFunctions?
FunctionChoiceBehavior.Auto() replaces it. Set it on PromptExecutionSettings or OpenAIPromptExecutionSettings, and the connector then advertises the functions and invokes them for you.
Can I force the model to call a specific function?
Use FunctionChoiceBehavior.Required() with a function list to force a call, though local server support varies. Fall back to Auto() and an explicit instruction if the server rejects the tool_choice value.
Do async plugin methods work with auto-invocation?
Yes. Methods returning Task or Task<string> are awaited by Semantic Kernel. Keep return values short, as strings or compact JSON, so they do not crowd a small context window.