A Practical Guide to Running Open-Source LLMs Locally with Function Calling
This guide explains why teams run open-source large language models on their own hardware, how function calling supports agents, and what to check before production use. It covers licenses, hardware sizing, a four-step deployment flow, a minimal agent loop, cost tradeoffs, common failures, and a practical selection sequence.
1. Why locally hosted open-source models matter
Over the past year or two, the common way to use large language models has been a cloud inference API billed by input and output tokens. That path is fast to adopt, but it runs into clear limits in three situations.
First, data compliance. Customer records, internal code, and financial data that repeatedly leave the network or pass through a third-party server raise the cost of compliance review.
Second, usage cost. When an agent reasons across multiple turns and calls tools repeatedly, token use grows linearly with the number of calls. In high-frequency workloads, that bill is hard to ignore.
Third, control. Model version changes, rate limits, and service availability are decided by the provider. A production system has little certainty over those factors.
Running an open-source model locally is one technical response. Inference stays on your own devices or private servers, data does not leave the internal network, and call volume is not metered by an external vendor. It is not free of tradeoffs. Hardware spend, operational responsibility, and the model’s capability ceiling all belong in the evaluation. The rest of this guide covers capability, licensing, deployment, integration, and cost.
2. Core capability: function calling
Function calling means the model emits a structured request during a conversation—typically a function name and JSON arguments. The host application actually runs the function and returns the result to the model. The model does not access databases or the network itself. Side effects stay under program control.
This mechanism is the foundation of an agent. A typical flow is:
- The application gives the model descriptions of available tools, including name, purpose, and a JSON Schema for the parameters.
- The user asks a question, and the model decides whether a tool is needed.
- If so, the model returns the tool name and arguments.
- The application validates the arguments, runs the function, and appends the result to the context as a tool-role message.
- The model writes a final answer from that result, or requests another call.
To judge whether a local model can serve as an agent base, focus on three checks: whether it reliably emits valid JSON, whether it selects the right tool among several, and whether context stays consistent across multiple calls. These signals reflect engineering fitness better than a general Q&A score. Test with your own tool set at small scale before you commit.
3. Licenses and commercial boundaries
“Open source” covers a wide range of terms. Some weights are research-only. Others allow commercial use only under conditions or user-scale limits. Read the license text before you choose a model, and pay particular attention to:
- Whether commercial use is allowed, including products or services you offer to customers that are based on the model.
- Whether you may modify or fine-tune the weights and publish a derivative.
- Whether redistribution is allowed, and which notices or copyright statements must travel with the files.
- Whether extra limits apply to user count, revenue, or field of use.
Permissive licenses usually allow commercial use, modification, and redistribution if you keep the copyright notice and license text. That lowers the compliance bar. It does not remove copyright questions about training data or compliance risk in model output. Teams should keep an internal usage policy and have legal review confirm the clauses that matter.
4. Hardware and environment
Local feasibility depends mainly on GPU memory or system RAM. A rough estimate is:
Required memory ≈ parameter count × bits per parameter ÷ 8 + runtime overhead
Runtime overhead includes the KV cache, activations, and the framework itself, and it usually grows with context length. For a 7-billion-parameter model at 4-bit quantization, the weights are about 3.5 GB. With overhead, 8 GB of VRAM can run short contexts. Larger models need more VRAM, or several GPUs in parallel.
Also weigh:
- Inference speed. Generation rate is mostly limited by memory bandwidth. Interactive apps usually need tens of tokens per second or more.
- Context length. Long context increases VRAM use sharply. Size the machine for the input lengths you actually see.
- Quantization. Lower precision cuts resource use and costs some accuracy. Compare quantization levels on the target task.
- Concurrency. A single local user and a shared multi-user service need very different capacity. The latter needs a dedicated inference service and load balancing.
5. Deployment steps
Local deployment usually has four steps.
Step 1: Prepare the runtime. Confirm that the operating system, drivers, and hardware acceleration libraries are compatible, and reserve enough disk for the model files.
Step 2: Obtain and verify the model. Download weights from a trusted source and check file hashes. Do not run binaries whose origin you cannot confirm.
Step 3: Start the inference service. The service is typically a local process that exposes an HTTP API. Bind it to 127.0.0.1 or an internal address. Do not expose it directly on the public internet.
Step 4: Validate behavior. Run a fixed set of test cases for output format, latency, and resource use. Record a baseline so later upgrades can be compared.
6. Connecting an agent: a function-calling example
The example below is a minimal agent loop. It assumes a local inference service that accepts a message list and tool definitions. Change the endpoint and response fields to match your deployment.
import jsonimport requests# Local inference endpoint; change to match your deploymentENDPOINT = "http://127.0.0.1:8000/chat"MAX_ROUNDS = 5 # Cap call rounds so the model cannot loop indefinitely# Tool description in JSON Schema formTOOLS = [{"type": "function","function": {"name": "get_weather","description": "Look up the current weather for a given city","parameters": {"type": "object","properties": {"city": {"type": "string", "description": "City name"}},"required": ["city"],},},}]def get_weather(city: str) -> str:# Sample implementation; call a trusted data service in productionreturn json.dumps({"city": city, "condition": "clear", "temp_c": 22}, ensure_ascii=False)# Allowlist: only functions registered here may runTOOL_IMPL = {"get_weather": get_weather}def chat(messages):resp = requests.post(ENDPOINT,json={"messages": messages, "tools": TOOLS},timeout=60,)resp.raise_for_status()return resp.json()["message"]def parse_arguments(raw):# Arguments may arrive as a string or as a dict; normalize bothreturn json.loads(raw) if isinstance(raw, str) else rawdef run_agent(user_input: str) -> str:messages = [{"role": "user", "content": user_input}]for _ in range(MAX_ROUNDS):msg = chat(messages)calls = msg.get("tool_calls")if not calls:return msg["content"]messages.append(msg)for call in calls:name = call["function"]["name"]if name not in TOOL_IMPL:# Reject unregistered tool names so the model cannot call unexpected functionsresult = json.dumps({"error": f"unknown tool: {name}"}, ensure_ascii=False)else:args = parse_arguments(call["function"]["arguments"])result = TOOL_IMPL[name](**args)messages.append({"role": "tool", "name": name, "content": result})raise RuntimeError("maximum call rounds exceeded; stopped")if __name__ == "__main__":print(run_agent("What is the weather in Beijing today?"))
The sample highlights a few engineering points.
- Allowlist. The model can trigger only functions you registered. It cannot run arbitrary code.
- Argument checks. In production, validate the type and range of
args, and restrict which resource paths the tool can reach. - Round limit. Stop the loop if the model gets stuck, so it does not burn compute indefinitely.
- Error feedback. When a tool fails, return the error to the model and let it retry or explain the failure to the user, instead of crashing the service.
7. Cost: what “zero marginal cost” actually means
Local inference removes the per-token unit price, but total cost is not zero. A full picture usually includes:
- One-time spend. GPUs, memory, storage, and other hardware.
- Ongoing cost. Power for the machines, plus cooling or facility charges.
- Labor. Engineering time for model upgrades, driver maintenance, monitoring, alerts, and incident response.
- Opportunity cost. If the local model is not capable enough, you may need extra human review or a fallback path.
A simple break-even check is enough to start. Let C be the monthly cloud token bill and H the monthly amortized cost of the local setup. Local hosting is more economical when C stays above H. Build H from hardware amortized over its expected life, plus power and operations labor. At low volume, the cloud service is often cheaper. At high volume, with sensitive data or a need for long-term stable operation, the local option is more compelling.
8. Common problems and how to investigate them
Unstable JSON. State the required output format in the prompt, and retry in the application when parsing fails. If failures stay frequent, switch to a larger model or one that handles structured output more reliably.
Wrong tool choice. Check whether tool descriptions are clear and whether names or purposes overlap. Describe when a tool applies and when it does not.
High latency. First confirm that low VRAM is not forcing memory swapping. Then check context length. Summarizing older messages can shrink the prompt.
Context lost after several calls. Confirm that every model output and tool result was appended to the message list, and that the context window has not exceeded the model limit.
Security. Do not concatenate model output into shell commands, SQL, or file paths. Escape or parameterize all external input, and require a human confirmation step for high-risk actions.
9. Summary and how to choose
Local open-source models fit teams that need data control, predictable cost, and operational certainty. Move through selection in this order:
- Define the workload, the tools you need to call, and typical input length.
- Read candidate licenses and confirm commercial use and redistribution terms.
- Pick parameter scale and quantization for your hardware, and compare quality on your own tasks.
- Build a minimal agent from the example above and test how stable function calling is.
- Using real call volume and operations effort, compare total cost of the local setup with the cloud API, then choose the architecture.
Function calling decides whether a model can be a reliable execution core for an agent. License terms and deployment cost decide whether it can enter production. Both need to be validated on real business data, not on generic leaderboards or marketing claims alone.
