Open-Source Stack and Local LLM Agents
Running everything yourself is very achievable. Knowing what you are now responsible for is the real work.
An open stack combines an open-weight model, a serving engine, an agent framework, retrieval, observability and evaluation. Check the license of every exact model file, give local models enough context window, verify what you download and remember that local does not automatically mean private or safe.
What you will learn: the layers of an open stack, the difference between open weights and open source, how to choose and license models, how to run a local agent, what to self-host for retrieval and which checks protect you.
Prerequisites: Set Up Your Agent Development Lab and Agent Tools, Function Calling and Tool Registries.
The example runs in November 2026 with Python 3.13 and only the standard library, using stand-in bytes instead of a real model. License and software facts were checked on November 28, 2026. This is general information, not legal advice about any license.
An open-source stack
| Layer | Examples | Select by |
|---|---|---|
| Model hub | Hugging Face | Publisher, license, files, history |
| Serving | Ollama, llama.cpp, vLLM, SGLang | Users, hardware, API needs |
| Framework | LangGraph, smolagents, others, or plain code | Control, state, maintenance |
| Vector search | pgvector, Qdrant, Milvus, OpenSearch | Scale, filtering, operations |
| Tracing | OpenTelemetry with an open backend | Agent step support and retention |
| Evaluation | Your cases with an open runner | Reproducibility and ownership |
Names in this table are examples, not endorsements. Licenses vary, and some projects offer an open core with paid features. Choosing Frameworks: Lock-In, Upgrades and Benchmarks covers frameworks, including smolagents from Hugging Face.
Open weights is not the same as open source
Many models publish their weights so that you can download and run them, while keeping training data and code private or adding use conditions. The Open Source Initiative has published a definition of open source AI that asks for more than downloadable weights. In everyday talk the terms blur, so read the actual license.
Licenses to check
| Family | Pattern in late 2026 |
|---|---|
| Permissive, such as Apache 2.0 or MIT | Broad use rights; OpenAI's gpt-oss models use Apache 2.0, and Google released Gemma 4 under it |
| Community or custom licenses | Conditions on scale, naming, use or region; Meta's Llama licenses are examples |
| Mixed within one family | Qwen licenses vary between repositories and releases |
| Research or non-commercial | Not usable for a product without further agreement |
Record for each model: repository, exact version, license text, any usage policy, restrictions on using outputs to train other models, and who reviewed it. Check derived and quantized copies too, since they inherit obligations and may be mislabeled.
Choosing an open model for agents
- Tool calling: does it produce valid, correctly typed calls in your serving setup?
- Context: can your hardware hold the length your tasks need?
- Instruction following: does it respect limits over many steps?
- Languages and domain: tested on your own material.
- Size and speed: acceptable task time, not only tokens per second.
- Safety behavior: how it handles hostile content and refusals.
- Lifecycle: publisher, update history and documentation.
Shortlist by license and hardware, then run the same evaluation set on each candidate. Public leaderboards rarely predict how a model handles your tools. See Choosing Models: Reasoning, Open-Weight and Hosted and Agent Benchmarks and Datasets.
Running a local agent
Ollama downloads and serves models on a laptop or server and offers OpenAI-compatible endpoints, so many clients work by changing the address. Context length is the setting that surprises people. The context length documentation lists default windows that depend on available video memory, starting at 4k tokens below 24 GiB, and advises at least 64,000 tokens for agents and coding tools. One way to set it is:
OLLAMA_CONTEXT_LENGTH=64000 ollama serve
A larger window needs more memory. After loading a model, check what was actually allocated and whether part of it spilled to the CPU, which slows everything. Also note that Ollama offers cloud-hosted models alongside local ones. If privacy is the reason for running locally, confirm that the model name you call runs on your machine.
Preflight checks for a local agent
The program refuses a model file whose digest does not match the approved value, and it shows what happens when a prompt exceeds the window.
"""Check model file identity and context budget before a local agent run."""
import hashlib
MODEL_BYTES = b"pretend these are model weights, version 3" * 1000
APPROVED = {"assistant-small:v3": hashlib.sha256(MODEL_BYTES).hexdigest()}
def verify(name, data):
if name not in APPROVED:
return "not on the approved list"
if hashlib.sha256(data).hexdigest() != APPROVED[name]:
return "file does not match the approved digest"
return "ok"
def tokens(text):
return len(text) // 4 + 1 # rough estimate; use the real tokenizer
def silently_truncate(messages, limit):
"""What a server does if it drops the oldest text to make room."""
kept, used = [], 0
for role, text in reversed(messages):
if used + tokens(text) > limit:
break
kept.append(role)
used += tokens(text)
return list(reversed(kept))
def preflight(messages, limit, reply_room):
used = sum(tokens(text) for _, text in messages)
if used + reply_room > limit:
return f"refused: needs {used + reply_room} tokens, window is {limit}"
return f"ok: {used} used, {limit - used} free"
messages = [
("system", "Never delete files. Ask before running commands. " * 12),
("tools", "tool schema " * 500),
("user", "Tidy up the build folder."),
("tool result", "listing line " * 900),
]
print("good file: ", verify("assistant-small:v3", MODEL_BYTES))
print("changed file: ", verify("assistant-small:v3", MODEL_BYTES + b"x"))
print("unknown model:", verify("assistant-small:latest", MODEL_BYTES))
for limit in (4096, 16384):
print(f"\nwindow {limit}")
kept = silently_truncate(messages, limit)
print(" silent truncation keeps:", ", ".join(kept))
print(" safety rules present: ", "system" in kept)
print(" preflight:", preflight(messages, limit, reply_room=1024))
Output:
good file: ok
changed file: file does not match the approved digest
unknown model: not on the approved list
window 4096
silent truncation keeps: user, tool result
safety rules present: False
preflight: refused: needs 5606 tokens, window is 4096
window 16384
silent truncation keeps: system, tools, user, tool result
safety rules present: True
preflight: ok: 4582 used, 11802 free
In the small window the simulated server keeps only the latest messages. The instruction never to delete files has gone, along with the tool definitions, while the request to tidy a folder remains. Real servers differ in what they trim and whether they report it, so measure with your own versions. The safe design does not depend on that behavior: count tokens with the model's tokenizer before sending, refuse or compact when over budget, and enforce dangerous limits in the tool layer, where truncation cannot remove them. The character-based estimate here is only for illustration.
Self-hosting embeddings and rerankers
Retrieval needs an embedding model, often a reranker and a database. They are smaller than generation models and are a common first self-hosted piece.
| Decision | Guidance |
|---|---|
| Embedding model | Choose on retrieval tests in your languages; changing it means re-indexing |
| Reranker | Add if tests show better ordering within your latency budget |
| Dimensions | Larger vectors cost storage and speed |
| Database | Prefer one your team already runs if it meets needs |
| Permissions | Filter by user rights at query time |
| Versions | Store model version with each vector |
See Multimodal, Embedding and Reranking Models and Embeddings, Vector and Hybrid Search, Reranking.
Local is not automatically safe
- A local inference API may accept any request without real authentication. Keep it bound to the local machine, or put an authenticating proxy in front.
- Model files can be dangerous in formats that run code when loaded. Prefer safetensors and review repository code before enabling it.
- A model on your laptop still obeys planted instructions in documents. Tool permissions and sandboxes matter as much as with a hosted model.
- Frameworks, plugins and MCP servers are software from others. Review, pin and update them.
- Check telemetry, update checks and cloud features in each component.
- Protect local conversation history and indexes, which collect sensitive material.
Supply Chain and Retrieval Poisoning and Code Execution and Sandboxing give the defensive patterns.
Manage versions deliberately
A tag such as "latest" can change what you run without any change on your side. Pin model digests, container images and packages. Keep an internal mirror so that a removed upstream file does not stop deployment. When updating, run the evaluation set, compare, then switch, keeping the previous set ready. Subscribe to security advisories for the components that handle untrusted input or hold credentials.
From laptop to team service
| Concern | Laptop | Shared service |
|---|---|---|
| Serving | Local runner | Engine built for concurrency |
| Access | One person | Authentication and quotas |
| State | Local files | Managed stores with backup |
| Tools | Your own permissions | Per-user delegated rights |
| Failure | Restart | Replicas, alerts and an owner |
| Records | Optional | Traces, audit and retention |
The jump is mostly operational. NVIDIA, vLLM and GPU Sizing covers sizing and Agent Fleets and Internal Platforms the shared services.
Mix local and hosted
A router can send sensitive or simple steps to a local model and hard ones to a hosted model, if policy permits. Decide by rules based on data classification, not by asking a model whether data is sensitive. Log which model served each step, and make failure closed: if the local model is unavailable, a restricted request should wait rather than leave the boundary. See Model Routing, Fallbacks and Gateways.
A practical first week
- Pick one task with ten to twenty test cases.
- Run one permissively licensed model locally and record the context setting.
- Add a single read-only tool and test its calls.
- Add retrieval over a small, non-sensitive document set.
- Record traces and score the cases.
- Try a second model with the same cases and compare quality and time.
Fit the model to the machine
Memory decides what you can run. The weights must fit, and so must the cache for the context window, which grows with window size and with the number of requests served at once. A quantized model needs less memory at some cost in quality.
| Situation | What to try first |
|---|---|
| Model will not load | Smaller model or stronger quantization |
| Loads but is very slow | Check how much runs on the CPU; reduce size or window |
| Fails on long tasks | Raise the window if memory allows, or compact history |
| Poor tool calls | Check template and parser, then try another model |
| Several users queue | Move to a shared serving engine |
Change one thing at a time and rerun the same cases. Keep a note of model, digest, quantization, window, runtime version and hardware beside each result, or you will be unable to explain why last month's setup behaved differently.
Observe and evaluate your own stack
Hosted platforms give you dashboards without asking. In an open stack you add them. Record each model call and tool call with timing, token counts, errors and the version of every component. The OpenTelemetry project provides vendor-neutral instrumentation, and Agent Tracing and OpenTelemetry shows how to apply it to agent steps. Keep evaluation cases in the repository with the configuration, so that a pull request changing a model also shows the change in results. Without this, upgrades become guesswork and regressions are found by users.
Plan for upkeep
- Name who watches security advisories for each component.
- Schedule updates, and keep a tested way to return to the previous set.
- Remove models, plugins and indexes that are no longer used.
- Check that projects you depend on are still maintained.
- Keep your tools behind your own interfaces so a framework can be replaced.
- Back up state and indexes, and know how long rebuilding takes.
A small stack that one person understands is better than a large one nobody dares to change. Add components when a measured need appears.
Give local agents narrow tools
Smaller models tend to benefit from simpler choices. Offer a handful of tools with distinct names, few parameters and clear descriptions. Validate every argument in code and return errors that explain how to correct the call. Run file and command tools inside a container or a dedicated user account with a restricted working folder and no stored credentials, and require confirmation before anything is removed or sent. These limits make the agent more reliable and cap the damage when the model misreads a request. Designing Tool Schemas and Contracts has more on shaping tools.
Common mistakes
| Mistake | Consequence | Instead |
|---|---|---|
| Default context window for agents | Instructions and history vanish | Set and verify the window |
| Assuming a model family has one license | Unplanned legal exposure | Check each repository and version |
| Exposing a local API on the network | Unauthorized use | Bind locally or authenticate |
| Loading untrusted model files and code | Code execution on your machine | Safe formats, review and isolation |
| Calling a cloud model by mistake | Data leaves the device | Allow-list model names and egress |
| Floating tags | Silent behavior changes | Pin digests |
Checklist
- Each model has a recorded license, source and digest.
- The context window fits real prompts with room to reply.
- Token budgets are checked before sending.
- Inference endpoints are not openly reachable.
- Dangerous actions are limited by tools and sandboxes.
- Components and plugins are pinned and updated.
- Evaluations run before any model or version change.
- Restricted data cannot fall back to external services.
Frequently asked questions
Can a local model power a useful agent?
Yes for many narrow tasks, depending on model, hardware and tools. Measure on your cases instead of expecting parity with the largest hosted models.
Is open source cheaper?
License fees may be absent while hardware and staff are not. Compare complete cost at your real volume.
Which model should a beginner try?
A small one with a permissive license that fits your memory with an adequate context window. Line-ups change too fast for a lasting recommendation.
Does running locally satisfy privacy law?
It can help with transfers, but purpose, access, retention and individual rights still apply. Ask your privacy team.
References
- Ollama: context length
- Ollama: OpenAI compatibility
- Open Source Initiative: Open source AI
- Safetensors documentation
- Hugging Face smolagents
- IEEE Spectrum: open AI models and licenses
Where to go next
Private, Air-Gapped and Sovereign Deployment
Run the stack inside strict boundaries.
NVIDIA, vLLM and GPU Sizing
Size serving for several users.
RAG Explained and Agentic RAG
Add retrieval to your local agent.