Skip to content

Using Local Models

Run models locally on your machine without needing API keys or internet access.

Choosing an Inference Engine

PatchPal works with any engine that supports tool calling. Which one fits best depends mostly on your hardware:

Your setup Suggested engine How to connect
Server/datacenter GPUs, or a shared server for several users vLLM (or SGLang) hosted_vllm/ prefix
A single consumer NVIDIA GPU (8–24 GB) running larger MoE models PolyStrata (keeps part of the model in system RAM) openai/ prefix
Apple Silicon, or the simplest setup Ollama or llama.cpp ollama_chat/ or openai/ prefix
Anything else with an OpenAI-compatible API (LM Studio, internal proxies, etc.) — openai/ prefix

Whichever engine you use, run a recent version. Many tool-calling problems with local models come from bugs in older engine versions (chat templates and tool-call parsing), not from the model.

For models without native function calling support, PatchPal includes a ReAct agent mode that uses text-based tool invocation instead of native function calling APIs.

For small context windows (64K or less, common with local servers), PatchPal uses TinyAgent once you set PATCHPAL_CONTEXT_LIMIT to your window size.

vLLM

vLLM is a high-throughput inference server (continuous batching, PagedAttention) with robust multi-turn tool calling. It's a good fit for GPU servers and for serving several users at once.

Important: vLLM >= 0.10.2 is required for proper tool calling support.

Using Local vLLM Server:

# 1. Install vLLM (>= 0.10.2)
pip install vllm

# 2. Start vLLM server with tool calling enabled
vllm serve openai/gpt-oss-120b \
  --dtype auto \
  --api-key token-abc123 \
  --tool-call-parser openai \
  --enable-auto-tool-choice

# 3. Use with PatchPal (in another terminal)
export HOSTED_VLLM_API_BASE=http://localhost:8000
export HOSTED_VLLM_API_KEY=token-abc123
patchpal --model hosted_vllm/openai/gpt-oss-120b

Using Remote/Hosted vLLM Server:

# For remote vLLM servers (e.g., hosted by your organization)
export HOSTED_VLLM_API_BASE=https://your-vllm-server.com
export HOSTED_VLLM_API_KEY=your_api_key_here
patchpal --model hosted_vllm/openai/gpt-oss-120b

Environment Variables: - Use HOSTED_VLLM_API_BASE and HOSTED_VLLM_API_KEY

Using YAML Configuration (Alternative):

Create a config.yaml:

host: "0.0.0.0"
port: 8000
api-key: "token-abc123"
tool-call-parser: "openai"  # Use appropriate parser for your model
enable-auto-tool-choice: true
dtype: "auto"

Then start vLLM:

vllm serve openai/gpt-oss-120b --config config.yaml

# Use with PatchPal
export HOSTED_VLLM_API_BASE=http://localhost:8000
export HOSTED_VLLM_API_KEY=token-abc123
patchpal --model hosted_vllm/openai/gpt-oss-120b

Example models for vLLM: - openai/gpt-oss-120b - OpenAI's open-source model (use parser: openai) - openai/gpt-oss-20b - Smaller variant, good for lower-resource setups (use parser: openai)

Special Notes for gpt-oss Models

The gpt-oss models (20B and 120B) are reasoning models that use chain-of-thought (CoT) to solve complex tasks. PatchPal automatically captures and passes back the reasoning content (enabled by default), which is critical for these models to maintain focus across multiple turns.

Key requirements for gpt-oss:

  1. Use the OpenAI tool call parser - Required for proper function calling
  2. Use Unsloth template (if using llama.cpp) - Contains fixes for proper reasoning handling
  3. Reasoning content is automatic - PatchPal captures reasoning_content from responses and passes it back in subsequent turns (enabled by default, disable with PATCHPAL_CAPTURE_REASONING=false if needed)
  4. Viewing reasoning (optional) - Set PATCHPAL_SHOW_REASONING=true to print the reasoning live, in dim text, as it streams

Example with vLLM:

# Start vLLM with gpt-oss-20b
vllm serve openai/gpt-oss-20b \
  --dtype auto \
  --api-key token-abc123 \
  --tool-call-parser openai \
  --enable-auto-tool-choice

# Use with PatchPal (reasoning content capture is automatic)
export HOSTED_VLLM_API_BASE=http://localhost:8000
export HOSTED_VLLM_API_KEY=token-abc123
patchpal --model hosted_vllm/openai/gpt-oss-20b

Occasional empty responses

Some local models can intermittently return an empty response (no content and no tool call), often after a tool result or on long/complex prompts. This is typically an inference-engine parsing/template bug, not a PatchPal issue — e.g. gpt-oss on vLLM (harmony-format parsing) or Gemma4 MoE on older Ollama (ollama#15428, fixed in Ollama 0.21+). The best fix is to run a recent inference engine (vLLM

= 0.10.2 / newer; Ollama >= 0.21). As a client-side safety net, PatchPal automatically retries empty responses before giving up — controlled by PATCHPAL_EMPTY_RETRY_MAX (default: 2; set to 0 to disable). If retries are exhausted, PatchPal returns a NO_RESPONSE: message rather than a misleading "task completed".

Example with llama.cpp:

# Start llama.cpp server with Unsloth template
llama-server \
  --model gpt-oss-20b-Q4_K_M.gguf \
  --chat-template unsloth \
  --port 8080

# Use with PatchPal via OpenAI-compatible endpoint (reasoning content capture is automatic)
export OPENAI_API_BASE=http://localhost:8080/v1
export OPENAI_API_KEY=dummy
patchpal --model openai/gpt-oss-20b

Performance characteristics: - Focus maintenance: Without reasoning content pass-back (PATCHPAL_CAPTURE_REASONING=false), the model loses focus after 15-20 steps - Multi-turn reliability: With reasoning content enabled (default), the model maintains context across many turns - Task completion: The reasoning content allows the model to track what it's done and what remains

Resources: - Blog: Proper tool calling with gpt-oss - Notebook: gpt-oss tool calling examples - Reddit: Discussion on gpt-oss setup

Tool Call Parser Reference: Different models require different parsers. Common parsers include: qwen3_xml, openai, deepseek_v3, llama3_json, mistral, hermes, pythonic, xlam. See vLLM Tool Calling docs for the complete list.

OpenAI-Compatible Endpoints

Any server that exposes an OpenAI-compatible REST API (e.g., vLLM, llama.cpp, LM Studio, PolyStrata, or an internal proxy) can be used with the openai/ prefix. Point OPENAI_API_BASE at the server and use the model name it serves:

export OPENAI_API_BASE=https://your-server.example.com/v1   # include the /v1 suffix
export OPENAI_API_KEY=your_api_key_here                     # any non-empty value if the server doesn't check keys
patchpal --model openai/<served-model-name>

For example, with a local vLLM server:

export OPENAI_API_BASE=http://localhost:8000/v1
export OPENAI_API_KEY=token-abc123
patchpal --model openai/openai/gpt-oss-120b   # "openai/" prefix + the model name vLLM serves

Or with a local PolyStrata server:

export OPENAI_API_BASE=http://127.0.0.1:8080/v1
export OPENAI_API_KEY=dummy                 # placeholder; any non-empty value
export PATCHPAL_CONTEXT_LIMIT=32768         # match the server's context window (64K or less enables TinyAgent)
patchpal --model openai/inkling-2-mini

# Or as a one-off command (variables apply only to this run):
OPENAI_API_BASE=http://127.0.0.1:8080/v1 OPENAI_API_KEY=dummy PATCHPAL_CONTEXT_LIMIT=32768 patchpal --model openai/inkling-2-mini

Notes:

  • openai/ vs hosted_vllm/: Both work with vLLM. hosted_vllm/ uses HOSTED_VLLM_API_BASE (no /v1 suffix, as in the examples above); openai/ uses OPENAI_API_BASE (with /v1) and works with any OpenAI-compatible server.
  • Unsupported parameters are dropped: When OPENAI_API_BASE is set, PatchPal tells LiteLLM to drop request parameters the server doesn't support.
  • Tool calling must be enabled on the server: e.g., vLLM needs --tool-call-parser and --enable-auto-tool-choice. If the server doesn't support function calling, use ReAct mode.
  • Set the context limit: PatchPal detects context limits from the model name, so set PATCHPAL_CONTEXT_LIMIT to the window the server provides (this also enables TinyAgent at 64K or less).

Ollama

Ollama v0.14+ supports tool calling for agentic workflows. However, proper configuration is critical for reliable operation.

Requirements:

  1. Ollama v0.14.0 or later - Required for tool calling support
  2. Sufficient context window - Default 4096 tokens is too small; increase to at least 32K

Recommended Settings for Local Models:

For better performance with local models (both Ollama and vLLM), especially smaller models (<20B params):

# Reduce tool confusion by limiting to 5 essential tools
# (only needed above 64K; TinyAgent uses these tools by default)
export PATCHPAL_MINIMAL_TOOLS=true

# Match your served context window (enables TinyAgent; see "Small Context Windows" below)
export PATCHPAL_CONTEXT_LIMIT=32768

# Disable web tools for offline/faster operation
export PATCHPAL_ENABLE_WEB=false

# Optional: disable streaming if Ollama tool calls are unreliable
# (may no longer be needed - see note below)
export PATCHPAL_STREAM_OUTPUT=false

# Use with Ollama
patchpal --model ollama_chat/glm-4.7-flash:q4_K_M

Benefits: - Fewer tools - Reduces tool confusion with smaller models - Tool call workaround - Disabling streaming was a workaround for Ollama tool calls being dropped or merged when streamed (openclaw/openclaw#5769). PatchPal now handles Ollama's streamed parallel tool calls correctly, so this may no longer be needed; try it if tool calls still fail

Invalid tool arguments

Smaller models sometimes send malformed tool arguments (e.g., two JSON objects in one call: {"path": "a.md"}{"path": "b.md"}). PatchPal doesn't run the call. It shows ✗ <tool>: Invalid arguments with the first 200 characters of the raw arguments, and tells the model how to fix the call (e.g., read_file reads one file per call, so make a separate call for each). It also repairs the stored call to valid JSON (the first JSON object, or {}).

Setup Instructions:

For Native Ollama Installation:

# Set context window size (required!)
export OLLAMA_CONTEXT_LENGTH=32768

# Start Ollama server
ollama serve

# In another terminal, use with PatchPal
patchpal --model ollama_chat/gpt-oss:120b

For Docker:

# Stop existing container (if running)
docker stop ollama
docker rm ollama

# Start with proper configuration
docker run -d \
  --gpus all \
  -e OLLAMA_CONTEXT_LENGTH=32768 \
  -v ollama:/root/.ollama \
  -p 11434:11434 \
  --name ollama \
  ollama/ollama

# Verify configuration
docker exec -it ollama ollama run gpt-oss:120b
# In the Ollama prompt, type: /show parameters
# Should show num_ctx much larger than default 4096

# Use with PatchPal
patchpal --model ollama_chat/glm-4.7-flash:q4_K_M

Verifying Context Window Size:

# Check your Ollama container configuration
docker inspect ollama | grep OLLAMA_CONTEXT_LENGTH

# Or run a model and check parameters
docker exec -it ollama ollama run glm-4.7-flash:q4_K_M
>>> /show parameters

Example Models for Tool Calling:

  • gpt-oss:120b - OpenAI's open-source model
  • glm-4.7-flash:q4_K_M - Z.ai's GLM model, excellent tool calling
  • qwen3.5 - Qwen3.5 model with good agentic capabilities
  • qwen3-coder-next - Specialized for coding tasks
  • gemma4:e4b - Google's Gemma 4 (~7.5B, 6.6 GB at Q4), runs on small GPUs; works well with TinyAgent at 16K (needs a recent litellm; older versions like 1.82.6 drop tool calls sent to Ollama, so the model repeats the same call in a loop)

Configuring Ollama for Reasoning Models (Qwen3.5, DeepSeek-R1, etc.)

Reasoning models like Qwen3.5:4b generate internal "Chain of Thought" (CoT) reasoning in hidden <think> tags before producing their final answer. This dramatically increases token consumption. By default, Ollama's context window (num_ctx) is only 2048-4096 tokens, which is insufficient for reasoning models—they will run out of space mid-thought and cut off before calling tools or writing code.

Critical Requirement: Increase Context Window Size

To use reasoning models with PatchPal, increase num_ctx to 32768 (recommended). On resource-constrained machines, 16384 can work with TinyAgent, but long reasoning outputs leave less room for work. Ollama already defaults to unlimited output generation (num_predict=-1), so the context window is the primary constraint.

Setting up with OLLAMA_CONTEXT_LENGTH (Simplest Method):

The easiest approach is to set the environment variable before starting Ollama:

# Set context window to 32K (recommended for reasoning models)
export OLLAMA_CONTEXT_LENGTH=32768

# Start Ollama
ollama serve

# In another terminal, configure PatchPal to match and run
export PATCHPAL_CONTEXT_LIMIT=32768
patchpal --model ollama_chat/qwen3.5:4b

Important: You must also set PATCHPAL_CONTEXT_LIMIT to match your Ollama context window. This tells PatchPal how much context is actually available, so compaction triggers at the right point. Use the same value as OLLAMA_CONTEXT_LENGTH (PatchPal already reserves space for the response). This also enables TinyAgent.

Alternative: Custom Modelfile (For Fine-Tuned Control):

If you want model-specific configuration or need to adjust the system prompt, create a custom Modelfile:

1. Create a Modelfile

Create a file named Modelfile (no extension):

FROM qwen3.5:4b

# Set the context window (input + output + reasoning)
PARAMETER num_ctx 32768

# Optional: System prompt to guide reasoning behavior
SYSTEM "You are a terminal agent. Keep reasoning structured and brief before executing tools."

Key parameters explained: - num_ctx 32768 - Total context window (includes input, output, and reasoning tokens) - SYSTEM prompt - Can help prevent excessive reasoning loops on simple tasks - Note: num_predict (max output tokens) defaults to -1 (unlimited, auto-capped at 10 * num_ctx), so you typically don't need to set it

2. Build the Custom Model

ollama create qwen-agent -f ./Modelfile

This creates a new model variant called qwen-agent with your custom configuration.

3. Run PatchPal with the Configured Model

# Set PatchPal's context limit to match
export PATCHPAL_CONTEXT_LIMIT=32768
patchpal --model ollama_chat/qwen-agent

Viewing the Reasoning (Optional):

PatchPal doesn't print reasoning by default; the spinner just shows "Generating..." with a token count. To watch it live in dim text, as the Ollama CLI does:

export PATCHPAL_SHOW_REASONING=true
patchpal --model ollama_chat/qwen3.5:4b

Common Issues Without Proper Configuration:

With default low context (2048-4096 tokens), reasoning models may: - ❌ Cut off mid-reasoning when context fills up - ❌ Fail to invoke tools or write code - ❌ Lose conversation history too quickly - ❌ Appear to "stall" or produce incomplete responses

With adequate context (32K+): - ✅ Complete reasoning before generating responses - ✅ Reliably invoke PatchPal tools - ✅ Generate complete code blocks - ✅ Maintain multi-turn conversation context

Advanced: Constraining Output Length (Optional):

In rare cases where you want to limit output length (e.g., to prevent extremely long responses), you can set num_predict:

FROM qwen3.5:4b
PARAMETER num_ctx 32768
PARAMETER num_predict 8192  # Limit output to 8K tokens

However, this is typically unnecessary since Ollama auto-caps output at 10 * num_ctx.

Other Reasoning Models:

This configuration applies to any model with internal CoT reasoning: - qwen3.5 (all variants: 4b, 8b, 14b, 32b) - deepseek-r1 (DeepSeek's reasoning model) - qwen-coder series - Any model using <think> tags or similar reasoning patterns

Additional Resources: - Reddit: Qwen3.5 on Apple Silicon - 2x faster with proper config - Ollama GitHub: num_predict defaults to -1 (unlimited) - Medium: Ollama options explained

Performance Note:

Ollama is the simplest way to get started, especially on Apple Silicon. For serving several users or running on GPU servers, vLLM usually gives higher throughput. See Choosing an Inference Engine.

Examples:

# Ollama (works with proper configuration)
export OLLAMA_CONTEXT_LENGTH=32768
patchpal --model ollama_chat/qwen3:32b
patchpal --model ollama_chat/gpt-oss:120b
patchpal --model ollama_chat/glm-4.7-flash:q4_K_M

# vLLM
patchpal --model hosted_vllm/openai/gpt-oss-120b

Small Context Windows (TinyAgent)

Local models are often served with small context windows (e.g., OLLAMA_CONTEXT_LENGTH=32768). When PATCHPAL_CONTEXT_LIMIT is 64K or less, PatchPal automatically uses TinyAgent, which:

  • Uses minimal tools by default
  • Caps each tool output to about 15% of the window and prompts the model to read selectively
  • Compacts into a short handoff note when the context fills up

PatchPal can't detect your server's window size, so set PATCHPAL_CONTEXT_LIMIT to match it:

# Typical: OLLAMA_CONTEXT_LENGTH=32768
export PATCHPAL_CONTEXT_LIMIT=32768

# Resource-constrained machines (e.g., gemma4:e4b or qwen3.5:4b with OLLAMA_CONTEXT_LENGTH=16384)
export PATCHPAL_CONTEXT_LIMIT=16384

patchpal --model ollama_chat/gemma4:e4b   # Shows "🔧 Tiny agent (context window 16,384 ≤ 65,536): ..."

Reasoning models like Qwen3.5 produce long outputs, so use 32768 if your machine can handle it.

PATCHPAL_TINY_MODE=true forces it on. TinyAgent doesn't apply in ReAct mode, which keeps its own compaction. See Small Context Windows for details.

ReAct Mode for Models Without Function Calling

Some local models (especially smaller ones) struggle with native function calling. For these models, PatchPal provides a ReAct (Reason + Act) agent mode that uses text-based tool invocation instead of function calling APIs.

Why ReAct Mode? Many smaller local models (<20B parameters) either don't support native function calling or perform poorly with it. Even models that technically support function calling may generate malformed JSON, skip required parameters, or fail to invoke tools reliably. ReAct mode sidesteps these issues by using simple text-based patterns that are easier for such models to follow.

What is ReAct?

ReAct is a prompting pattern where the LLM follows this loop:

  1. Thought: Reason about what needs to be done
  2. Action: Invoke a tool with parameters (formatted as text/JSON)
  3. PAUSE: Wait for the tool result
  4. Observation: Receive the tool's output
  5. Repeat or output final Answer

Instead of using native function calling APIs, the agent parses tool invocations from the model's text output.

When to Use ReAct Mode

Use ReAct mode when: - Your model doesn't support native function calling - Native function calling is unreliable for your model - You're using smaller models (<20B parameters) that struggle with function calling - You want text-based tool invocation for debugging/transparency

Available Tools

ReAct mode includes these tools by default:

  • read_file - Read file contents
  • read_lines - Read specific lines from a file
  • write_file - Create or overwrite files
  • edit_file - Find and replace in files
  • run_shell - Execute shell commands
  • grep - Search for patterns in files
  • find - Find files by pattern or list directory contents
  • web_search - Search the web
  • web_fetch - Fetch webpage content

You can limit tools if needed:

agent = create_react_agent(
    model_id="ollama_chat/your_model",
    enabled_tools=["read_file", "write_file", "edit_file"]
)

Enabling ReAct Mode

CLI:

# Use ReAct mode with any model
export PATCHPAL_REACT_MODE=true
patchpal --model ollama_chat/llama3.2

# Or inline
PATCHPAL_REACT_MODE=true patchpal --model ollama_chat/qwen2.5

# Limit tools using environment variable
export PATCHPAL_REACT_MODE=true
export PATCHPAL_ENABLED_TOOLS="read_file,write_file,edit_file"
patchpal --model ollama_chat/llama3.2

Python API:

from patchpal import create_react_agent

# Basic usage
agent = create_react_agent(model_id="ollama_chat/llama3.2")
response = agent.run("List the Python files")
print(response)

# With custom tools
def calculator(x: int, y: int) -> str:
    """Add two numbers together."""
    return str(x + y)

agent = create_react_agent(
    model_id="ollama_chat/qwen2.5",
    custom_tools=[calculator]
)
response = agent.run("What is 42 plus 58?")

Best Practices

  1. Start with defaults - These tools are available by default:

    PATCHPAL_REACT_MODE=true patchpal --model ollama_chat/llama3.1:8b
    

  2. Limit tools for simpler tasks - Fewer tools can improve focus:

    agent = create_react_agent(
        model_id="ollama_chat/your_model",
        enabled_tools=["read_file", "write_file", "edit_file"]
    )
    

  3. Add custom instructions - Guide the model's behavior:

    agent = create_react_agent(
        model_id="ollama_chat/your_model",
        custom_instructions="""
        - Answer general questions directly without tools
        - Only use tools for file/code operations
        - Provide concise answers
        """
    )
    

Native Function Calling vs ReAct

Aspect Native Function Calling ReAct Mode
Model Support Requires function calling Works with any LLM
Reliability High (API-enforced) Good (prompt-based)
Performance Generally faster Comparable
Setup Zero config (if supported) Single env var
Parallel Tools Supported Sequential only
Debugging Opaque API calls Visible text reasoning

Troubleshooting ReAct Mode

Model not following format: - Try a better/larger model - Simplify the task into smaller steps - Add more explicit instructions via custom_instructions

Tool calls not being parsed: Ensure model outputs exact format:

Action: tool_name: {"param": "value"}
PAUSE

Agent looping without finishing: - Reduce max_iterations to fail faster - Try a model that better understands completion signals - Add explicit completion instructions

Implementation Details