Running a Tool-Calling Agent Locally on Mac: Qwen3-0.6B + Ollama

Without changing the SDK, just change the base_url. Run Qwen3-0.6B locally with Ollama, integrating it into an OpenAI-compatible agent loop, and clarify the pitfalls of the thinking mode and tool_calls that may flip with version changes.

About 2,837 words 6 min read

0. Quick Start in Five Steps

If you're in a hurry, four commands and two lines of code will suffice; see the details and pitfalls below:

brew install ollama
brew services start ollama
ollama pull qwen3:0.6b
curl -s http://localhost:11434    # Expected output: Ollama is running
client = OpenAI(base_url="http://localhost:11434/v1", api_key="ollama")
# When calling, use model="qwen3:0.6b" and provide a strong system prompt:
# "Must call tools when external information is needed, do not answer yourself."

1. A Realization: SDK is Just an HTTP Client

The OpenAI SDK does not require the server to be OpenAI. As long as the service pointed to by base_url implements a compatible /v1/chat/completions and returns the same format of JSON, the SDK will work normally. Therefore, the key to running open-source models locally can be summed up in one sentence: Do not change the SDK, just replace base_url and model.

01-two-backends

api_key="ollama" is a placeholder: Ollama does not validate it, but the SDK requires a non-empty string; otherwise, it will throw an error during initialization.

2. Installation, Startup, and Some Easily Overlooked Behaviors

brew services start ollama will register Ollama as a launchd background service, starting automatically at boot and listening on localhost:11434. If you don't want it to run persistently, you can manually use ollama serve. Pull the model using ollama pull qwen3:0.6b, which is about 522 MB.

CommandFunction
ollama listLists locally downloaded models and their accurate tags
ollama psShows models currently resident in memory and their remaining lifespan
ollama stop qwen3:0.6bActively unloads, immediately freeing several GB
ollama show qwen3:0.6bDisplays context length, quantization method, parameter count, and template
ollama run qwen3:0.6bOpens a terminal dialogue to get a feel for the model's capabilities

Two behaviors that are easily misjudged: Models will reside in memory, with a default keep_alive of 5 minutes. When continuously switching models for debugging, you may see two or three models hanging in ollama ps, which can consume memory; the first call requires waiting for loading. The 0.6B model is almost imperceptible, but for 4B/8B models, it can take several seconds, so don't misinterpret this as "the model has slowed down."

To allow another machine on the same Tailscale network to connect: set launchctl setenv OLLAMA_HOST "0.0.0.0:11434" and then restart the service. Note that Ollama does not validate api_key, so this effectively exposes it on the local network; only do this on trusted networks.

3. A Request Passing Through Four Layers

Breaking down the link into four layers allows you to pinpoint where the issue lies during troubleshooting:

02-four-layers

Issues in the first three layers will throw exceptions—connection refused, model name does not exist, api_key is empty, and the stack trace will tell you where the problem is. Issues in the fourth layer do not throw exceptions—HTTP 200, valid JSON, and the loop ends normally, but the content is incorrect. Therefore, the troubleshooting order should be to first penetrate the first three layers, and then figure out why the model is not behaving as expected. Suspecting the model first can easily waste an hour on a typo in the base_url.

4. Verify with curl Before Writing Python

This command bypasses the SDK and your loop code, returning whatever Ollama outputs directly:

curl -s http://localhost:11434/v1/chat/completions \
  -H "Content-Type: application/json" \
  -d '{
    "model": "qwen3:0.6b",
    "messages": [
      {"role": "system", "content": "Must call tools when external information is needed, do not answer yourself."},
      {"role": "user", "content": "What is the weather like in Beijing now?"}
    ],
    "tools": [{"type": "function", "function": {
      "name": "get_weather", "description": "Query the current weather for a specified city",
      "parameters": {"type": "object", "properties": {"city": {"type": "string"}}, "required": ["city"]}
    }}]
  }' | python3 -m json.tool

How to interpret the results:

  • If choices[0].message.tool_calls is a non-empty array → the link is fully operational, and you can go back to writing Python.
  • If JSON is returned but tool_calls is null, and content contains a plausible weather response → the model is reasoning. Strengthen the system prompt; if that doesn't work, the 0.6B model may not have sufficient capability, so switch to a larger model from Section 9.
  • If there is no JSON at all (e.g., Connection refused / 404) → there is a problem with the service or URL, and do not proceed to adjust the model.

By the way, fields like reasoning_effort that are not present in the SDK type signature but are recognized by the server should be top-level fields in curl, while in the Python SDK, they must be included in extra_body; sending them directly will be rejected by the SDK. The final JSON sent out from both sides is the same.

5. A Minimal Loop That Can Run Directly

03-loop-flow

Combining the previous snippets, the following code can be pasted into a single cell in your notebook. The tools are two mock implementations; the focus is on the structure of the loop—only the execute_tool function needs to be replaced with the real function in a real project:

import json
from openai import OpenAI

client = OpenAI(base_url="http://localhost:11434/v1", api_key="ollama")
MODEL = "qwen3:0.6b"

tools = [
    {"type": "function", "function": {
        "name": "get_weather", "description": "Query the current weather for a specified city",
        "parameters": {"type": "object", "properties": {"city": {"type": "string", "description": "City name"}}, "required": ["city"]},
    }},
    {"type": "function", "function": {"name": "get_time", "description": "Get the current time", "parameters": {"type": "object", "properties": {}}}},
]

def execute_tool(name, args):
    if name == "get_weather":
        return {"city": args.get("city"), "temp_c": 31, "sky": "clear"}
    if name == "get_time":
        return {"now": "2026-08-26 14:20"}
    return {"error": "unknown tool: %s" % name}

messages = [
    {"role": "system", "content": "You are an assistant. Must call tools when external information is needed, do not guess."},
    {"role": "user", "content": "What is the weather like in Beijing now? What time is it?"}
]

for turn in range(6):                      # Upper limit to prevent the model from looping indefinitely
    resp = client.chat.completions.create(
        model=MODEL, messages=messages, tools=tools,
        temperature=0,                     # Use low temperature for structured output
        # extra_body={"reasoning_effort": "none"},  # See Section 6: Adding this on the new Ollama makes it worse
    )
    msg = resp.choices[0].message
    messages.append(msg)                   # ① Assistant's message must be appended first

    if not msg.tool_calls:                 # No tool calls = this is the final answer
        print(msg.content)
        break

    for call in msg.tool_calls:            # ② Each tool_call must have a corresponding tool message
        args = json.loads(call.function.arguments or "{}")
        result = execute_tool(call.function.name, args)
        print("  ↳ Calling %s(%s)" % (call.function.name, args))
        messages.append({
            "role": "tool",
            "tool_call_id": call.id,       # ③ Missing this id will lead to a 400 error in the next round
            "content": json.dumps(result, ensure_ascii=False),
        })
else:
    print("Exceeded maximum rounds without convergence, likely the model is repeatedly requesting the same tool.")

The three marked areas are the most prone to errors: ① The assistant's message must be appended back first, and it must include tool_calls—if you only append the tool results, the server will think a tool message has appeared out of nowhere; ② Each tool_call must have a corresponding tool message; if the model requests two tools at once, you need to append two messages; ③ The tool_call_id must be returned exactly as is; this is the only clue for the model to match results with requests.

04-messages-growth

Figure 4 brings two direct consequences. Cost grows quadratically with the number of rounds—while cloud services charge by token, running locally is free but can slow down significantly and approach context limits. Tool return values must be controlled in length—a tool returning several thousand words of JSON will be sent in every subsequent round, which will almost certainly push the previous system prompt out of the window on a small model. The practical approach is to trim the results in execute_tool to only the fields that the model truly needs.

6. Thinking and Tool Calls: A Conclusion That Flipped with Version Changes

Qwen3 is a "hybrid reasoning" model that defaults to outputting reasoning before providing an answer. The phenomenon initially recorded in this note was that under default configuration, qwen3:0.6b would determine that a tool should be called in the reasoning text but would not output a proper tool_calls field in the final response—assistant_message.tool_calls would always be None, and the loop would treat it as the final answer. The solution at that time was to use extra_body={"reasoning_effort": "none"} to turn off reasoning entirely (the native API's think: false does not work through the /v1 compatibility layer; this field must be used).

On 2026-08-26, retesting on Ollama 0.32.1, the conclusion flipped.

05-success-rate

Why? Because the new version of Ollama has separated the reasoning content into an independent reasoning field, no longer mixed in with content:

{
  "role": "assistant",
  "content": "",
  "reasoning": "Okay, the user asked what the weather is like in Beijing now. I need to use the provided weather query tool…",
  "tool_calls": [{"id": "call_ow91rvfb", "type": "function",
                  "function": {"name": "get_weather", "arguments": "{\"city\":\"Beijing\"}"}}]
}

Reasoning no longer occupies content, so the solution of "turning off reasoning" has lost its premise. Moreover, reasoning_effort: "none" does indeed take effect—after adding it, the response does not even contain the reasoning field—however, turning off reasoning is a net loss for 0.6B: without the reasoning step, it answers instinctively and does not call tools. The smaller the model, the scarcer the resource of reasoning at each step; cutting out any step can lead to collapse.

The real leverage lies in the system prompt. In Figure 5, any line with a strong system prompt has a success rate of 8/8, including the combination that would drop to 0/8 when used alone.

7. What the /v1 Compatibility Layer Recognizes and Does Not Recognize

Ollama's /v1/* is a layer of translation, not a complete implementation.

UsableCaution
POST /v1/chat/completions: supports tools / tool_choice / streamapi_key is not validated at all—when exposed externally, the service is unprotected
GET /v1/models: equivalent to ollama listResponse includes a reasoning field not present in OpenAI's specification; the SDK does not map it to a property, must be accessed via resp.model_dump()
POST /v1/embeddings: for local vector retrievalNative API fields like think, options, etc., are silently discarded when reaching /v1, without error—this is the root of the pitfall in Section 6
Context length is determined by Ollama, not by the request: the default num_ctx is far less than the model's nominal value

The symptom of the last point is "after chatting for several rounds, the model suddenly does not recognize the system prompt." The JSON Schema for tools itself occupies a significant number of tokens, and combined with the accumulated history, it can easily be truncated without your notice. To change this, use a Modelfile to solidify a new tag (this layer of /v1 cannot accept it):

cat > /tmp/Modelfile <<'EOF'
FROM qwen3:0.6b
PARAMETER num_ctx 8192
EOF
ollama create qwen3-8k -f /tmp/Modelfile     # After this, use model="qwen3-8k"

Increasing num_ctx will proportionally consume memory (KV Cache grows linearly with context). Upgrading from 0.6B to 8K is fine, but going from 8B to 32K requires checking available memory first.

8. Cloud vs Local

DimensionOpenAI Cloud (gpt-4o-mini)Local Ollama (qwen3:0.6b)
CostCharged by tokenFree, unlimited
Network / PrivacyRequires internet, data leaves the machineCompletely offline, data stays on the machine
LatencyNetwork round trip + queueLocal inference, small models are usually faster
Tool calling reliabilityVery stableRequires strong system prompts; multiple tools may be missed
Reasoning qualityHighLimited
Context128KLimited by num_ctx
ConcurrencyNaturally supportedSingle machine serial, multiple requests queue for memory
MemoryDoes not occupy local machine0.6B occupies about 1 GB resident, 4B about 4 GB

9. Switching to a Larger Local Model

The 0.6B model is sufficient to establish the link, but multi-tool orchestration is unstable (in practice, it may only call one tool, while another question is answered instinctively). To switch to a larger Qwen3 model, simply change one tag:

ollama pull qwen3:1.7b   # or qwen3:4b
06-model-sizes

A practical division of labor: Use 0.6B for coding, use 4B for actual work. The 0.6B model loads quickly and iterates fast, suitable for verifying that the loop logic is correct; once the logic is confirmed, switch to 4B to see the real effect—only the model= line needs to be changed.

10. Quick Reference for Errors

SymptomCauseSolution
model 'Qwen3-0.6B' does not existclient = OpenAI() defaults to connecting to the cloud; or local tag is incorrectEnsure base_url points to localhost:11434/v1, use the tag from ollama list for model=
insufficient_quotaOpenAI account has no quotaAccount issue, not a code issue
Connection refusedOllama is not startedbrew services start ollama, verify with curl localhost:11434
400, indicates tool message is invalidDid not append the assistant message with tool_calls; or missed tool_call_idFollow the order in Section 5 ①②③
Stops following system prompts after a few roundsHistory exceeds num_ctx, system prompt is truncatedTrim tool return values; use Modelfile to create a tag with a larger num_ctx
Loop does not stop, repeatedly calls the same toolSmall model does not realize the tool has returnedSet a maximum round limit; clarify tool results; switch to a larger model
Clearly should call a tool but answers instinctivelySystem prompt is not strong enough; or copied old conclusions with reasoning_effort: "none"Strengthen system prompt; remove reasoning_effort and retest
Same piece of code works inconsistently0.6B output variance is significantLoop 8 times to measure success rate before concluding; temperature=0 can help converge some

Conclusion

Ultimately, this experience taught me not just how to use Ollama, but a mindset towards local small models: Every "best parameter" is an empirical result from a specific version and model, not a rule. Making curl verification and 8 times looping a muscle memory is more useful than memorizing any single conclusion.

By the way, the Qwen3-0.6B running here is a standard decoder-only Transformer. If reading theory gets dull, open ollama show qwen3:0.6b and compare the config item by item with the textbook; it's the best way to review.

References: Ollama API documentation and OpenAI compatibility notes (github.com/ollama/ollama/docs), Qwen3 model page (ollama.com/library/qwen3), OpenAI function calling documentation.