Sub topic 14
When to use a self-hosted or local model
This chapter assumes you have read the earlier chapters on data flow and provider data policies. You should know what a prompt, context, and telemetry are. You should be comfortable with a command line, HTTP APIs, and environment variables.
Earlier chapters showed how to reduce risk when code goes to a hosted provider. This chapter covers the other option: keeping the model on hardware you control, so prompts never leave it.
Local versus self-hosted
The two terms describe different trust boundaries.
- Local model: the model runs on your own laptop or workstation. Tools such as Ollama, llama.cpp, and LM Studio do this. Prompts stay on that machine.
- Self-hosted model: the model runs on a server your organization controls. That might be a GPU box in your data center or a private cloud account. Many people share it, and prompts cross your network to reach it.
- Hosted API: a provider runs the model and you send prompts over the internet. Your protection comes from its contract and policy terms.
In the first two cases you remove the provider as a recipient of your data. You do not remove every risk. You move responsibility for the model, the server, the logs, and the access controls onto yourself.
What you gain
Running the model yourself changes the data flow in four ways.
- No third-party retention or training. You do not need to interpret a provider's retention window, plan terms, or opt-out settings, because the provider never receives the prompt.
- A smaller set of recipients. The only parties who can see a prompt are the machine's users and anyone with access to its logs.
- Control over network paths. You can run the model on a host with no outbound internet access. That also limits what a compromised or tricked agent can send out.
- Compliance fit. Some contracts, export rules, or regulations forbid sending certain data to outside processors. A self-hosted model can satisfy those rules where a hosted API cannot.
What you do not gain
Local models are easy to oversell as "safe". The following risks remain.
- Prompt injection still works. A model reading a hostile README or web page can be steered by it, whether it runs locally or not. If the agent can run commands, it can still read your
.envand pass it to another tool. - The client may still phone home. The editor plugin, agent, or desktop app in front of the model can send telemetry or call hosted services. A local model behind a cloud-connected client is not local.
- Secrets still land in logs. Chat history, shell history, and server request logs on your machine can store pasted credentials in plain text.
- Quality and context limits. Small models that fit on a laptop are weaker at long-context reasoning and tool use. If the model is poor, people paste code into a hosted chat instead. That is the worst outcome.
- You own patching. Inference servers are software with vulnerabilities. A server bound to every network interface with no authentication is an open door.
Decision criteria
Use the data class from your threat model to decide. The table gives a starting point. Adjust it to your own policy and contracts.
| Situation | Reasonable choice |
|---|---|
| Open-source code, public docs, generic questions | Hosted API, with the usual hygiene |
| Proprietary code, no regulatory limit, provider offers a business plan with no training and short retention | Hosted API on that plan |
| Code under a contract that bars third-party processing | Self-hosted or local |
| Regulated data (health, payment, government) | Self-hosted, or a hosted service your compliance team has approved |
| Unreleased security fixes, cryptographic key handling, incident data | Local or self-hosted |
| Real credentials or customer records | Not in any model. Remove or mask them first |
The last row is the important one. Moving a model onto your machine does not make it acceptable to paste a production database password into it. Secrets belong in a secrets manager, not in prompts.
Running a model locally
Ollama is one common way to run a model on your own machine. These commands download a model once and then run it with no network access to a provider.
ollama pull llama3.1:8b
ollama run llama3.1:8b "Explain what a .gitignore negation rule does."Ollama also exposes an HTTP API on your machine. The Python script below calls it and refuses to send the prompt anywhere except a loopback address. That guard protects you if someone later changes the URL through an environment variable.
import json
import os
import urllib.request
from urllib.parse import urlparse
ALLOWED_HOSTS = {"127.0.0.1", "localhost", "::1"}
def ask_local(prompt: str, model: str = "llama3.1:8b") -> str:
base = os.environ.get("LOCAL_LLM_URL", "http://127.0.0.1:11434")
host = urlparse(base).hostname
if host not in ALLOWED_HOSTS:
raise ValueError(f"Refusing to send prompt to non-local host: {host}")
body = json.dumps({"model": model, "prompt": prompt, "stream": False}).encode()
request = urllib.request.Request(
f"{base}/api/generate",
data=body,
headers={"Content-Type": "application/json"},
)
with urllib.request.urlopen(request, timeout=120) as response:
return json.load(response)["response"]
if __name__ == "__main__":
print(ask_local("Explain what this regex matches: ^AKIA[0-9A-Z]{16}$"))The script needs the Ollama service running and the model already pulled. It uses only the standard library.
Checking that it is really local
Do not assume the setup is private. Verify it.
- Check the bind address. The inference server should listen on loopback only. On Linux, run
ss -ltn | grep 11434. You want127.0.0.1:11434. If you see0.0.0.0:11434or*:11434, other machines on your network can reach it. - Watch outbound connections. Run the client for a few minutes with a tool such as
lsof -ior your firewall's log. Look for connections to anything other than your own host. - Read the client's settings. Look for telemetry, crash reporting, "improve the product" options, and cloud sync of chat history. Turn off what you do not need.
- Test with the network off. Disconnect from the network and run a prompt. If it works, the model itself is local. If the client fails, it was calling something remote.
For a shared self-hosted server, add authentication and TLS, or put it behind your existing gateway. Decide who may read the request logs and how long you keep them. Prompts stored in those logs are sensitive data.
Model supply chain
Downloaded weights are third-party artifacts, so apply the same suspicion you would to a package.
- Download from the publisher's official repository or a registry your organization approves.
- Prefer formats that cannot run code on load, such as safetensors or GGUF. Python pickle-based checkpoints can execute code when loaded.
- Record the model name, version, and checksum so you can reproduce and audit the setup.
- Read the license. Some models restrict commercial use or require attribution.
Costs and limits
Self-hosting has real costs, and you should weigh them before committing.
- Hardware. A model that handles code well may need a GPU with a lot of memory. Quantized versions reduce memory use but also reduce quality.
- Operations. Someone must update the server, monitor it, and manage access.
- Capability gap. The best hosted models are usually stronger than what you can run locally, especially for multi-step agent work.
- Latency and throughput. A shared server slows down when many developers use it at once.
A common compromise is a split policy. Use a local or self-hosted model for restricted repositories. Use an approved hosted plan for everything else. The team policy chapter that follows covers how to write that rule down.
Exercise
A teammate says, "We switched to a local model, so we can stop using .env ignore rules and redaction." Give two reasons this is wrong, and one check you would run to confirm the setup is really local.
Show answer
First, a local model can still be steered by prompt injection, and an agent that can read .env can pass the values to another tool or write them to a log, so ignore rules and agent limits still matter. Second, chat history, shell history, and server logs on the machine can store pasted secrets in plain text, so redaction and secret hygiene still matter. To confirm the setup is local, check the bind address with ss -ltn | grep 11434 and confirm it shows 127.0.0.1, then run a prompt with the network disconnected. If the client fails offline, it depends on a remote service.
Exercise
Your company has a contract that forbids sending customer code to third-party processors. A developer wants AI help on that code and can only run an 8B-parameter model on a laptop, which performs poorly on the task. What are two acceptable responses, and which response should you avoid?
Show answer
Acceptable: ask for a shared self-hosted server with a stronger model inside the company's approved environment, or narrow the task to something the small model handles well, such as explaining a short function or writing a test for an isolated piece. Avoid pasting the code into a hosted chat because the local model is not good enough, since that breaks the contract and is the failure that weak local models tend to cause.