Self-Hosting Coding LLMs: How to Choose an Inference Engine and Wire Up Tool Calling
A practical guide to deploying open-source coding LLMs on your own hardware. It explains how to pick a high-throughput inference engine by profiling your request pattern rather than comparing spec sheets, and why engine choice is only the starting point. The article covers the four facts every team must understand before wiring a model into a coding agent, walks through a complete order-query tool-call example with reference code, contrasts read-only tools with write operations like refunds, and details authorization, task-switching, and observability on the application side. You'll get a reusable decision framework, six rules for validating tool results, a troubleshooting table, and an implementation checklist for keeping a self-hosted setup both fast and reliably integrated.
1. Background: Why Coding Agents Are Hard to Wire Up
Over the past two years, more and more teams want to deploy open-source LLMs with strong coding ability on their own compute and then connect them to command-line coding agents. These tools typically read and write workspace files, run test commands, and complete tasks like looking up documentation or querying orders by calling external tools. The benefits of self-hosting are straightforward: data never leaves the internal network, costs stay predictable, and the model can be fine-tuned to match the team’s code style.
But there’s a full engineering chain between “getting the model to run” and “reliably connecting it to an agent.” The first fork teams run into is usually which inference engine to choose. If the topic were “which of two specific engines is stronger,” that’s actually the wrong question. A better framing is: under your own request profile, which technical approach is the better match, and what capabilities does the application side still need to fill in.
This article discusses two mainstream categories of high-throughput inference engines:
- Category A: Known for continuous batching, paged memory management, and general-purpose scheduling, with rich parallelism strategies and broad model and hardware coverage.
- Category B: Known for prefix-cache reuse, organizing cache blocks with a radix tree to reuse shared prefixes at finer granularity. Repeated prefixes such as system prompts and repository context hit the cache efficiently.
The two categories overlap heavily in features. Rather than assuming a conclusion, this article offers a reusable judgment framework.
2. Selection: Use Request Profiling Instead of Parameter Comparison
When choosing a self-hosted engine, the first step is not to read the spec table but to characterize your own request profile:
- What the input looks like: How many tokens does an average single-turn request carry? Are system prompts and repository files carried repeatedly across multiple turns?
- How it gets called: Mostly short completions, or multi-turn tool-call chains? How large is the concurrency?
- What you’re sensitive to: Do you care most about time-to-first-token (TTFT), time-per-output-token (TPOT), or overall throughput?
- Which model you use: Parameter count, context window, whether it’s been quantized?
- Operational capacity: Does the team have experience maintaining inference services?
Once the profile is clear, you can compare across the dimensions below. Note that the table describes the typical characteristics of each technical approach and does not represent any specific version. Actual support should be confirmed against the official documentation for the relevant version and your own benchmarks.
| Dimension | Category A engines | Category B engines | Why it matters for coding |
|---|---|---|---|
| Scheduling & batching | Continuous batching with dynamic batching of long and short requests | Also supports continuous batching, often with chunked prefill | When short completions and long requests run together, avoids a long request monopolizing compute for too long |
| Prefix caching | Usually offers optional prefix caching | Prefix caching is a core design, organized around shared-prefix reuse | Shared system prompts and repository context skip repeated prefill |
| Parallelism & scaling | More mature tensor parallelism, pipeline parallelism, multi-instance strategies | Also supports tensor and pipeline parallelism and multi-node deployment | Splitting is needed when a large model won’t fit on a single card; horizontal scaling when concurrency rises |
| Quantization & precision | Supports many quantization methods | Also supports many quantization methods | Low-bit quantization like 4-bit saves memory but code-generation quality must be verified |
| Structured output | Supports constrained decoding, tool-call parsing, and similar mechanisms | Also supports them | Determines whether the model can reliably produce valid tool-call arguments |
| Interface compatibility | Provides HTTP APIs compatible with mainstream cloud model services | Also provides them | Existing client code written against those APIs needs minimal changes |
| Monitoring metrics | Rich metrics for throughput, latency, queueing, cache hits, etc. | Also emits runtime metrics | The basis for capacity planning and alerting |
| Ecosystem & operations | Large community, plenty of docs and troubleshooting posts | Active community, more material in cache-reuse scenarios | Affects how fast the team can debug |
A few points are worth emphasizing:
- Cache gains depend on request structure. Category B engines’ advantage rests on there being many shared prefixes across requests. If requests barely overlap in input, this advantage shrinks noticeably.
- Coding requests aren’t homogeneous. There are both short requests like single-line or snippet completion and long ones like whole-repo Q&A and multi-turn tool-call chains. Category A engines have accumulated more in general scheduling and heterogeneous requests; Category B engines are more efficient on repeated prefixes. Which is the better fit depends on your request mix.
- Benchmark with real traffic. Don’t rely only on general leaderboard scores. Collect real requests covering high concurrency, long context, and sustained output; measure TTFT, TPOT, throughput, and P99 latency; fold runtime metrics into a single monitoring system; then compare before deciding.
3. Four Facts to Settle Before You Integrate
Choosing an engine is just the beginning. Before wiring it into a coding agent, understand what the inference service “can do” and “won’t do.”
3.1 One tool call needs at least two model calls
- First call: the model analyzes the user’s intent and returns
tool_calls, meaning “I need to look up order A100234”; - The application side executes the tool;
- Second call: the application appends the tool result back to the conversation as a
toolmessage, and the model generates a natural-language answer based on it.
A task that involves N tool calls produces at least N+1 model calls. A coding flow of reading files, running tests, and fixing them multiplies the call count, and the context grows with it.
3.2 The inference service does not enforce business authorization
The inference service only generates tokens. It doesn’t know who the caller is, whether they have permission, or whether a refund can go through. Authorization must happen on the application side, and before the model sees any business data.
3.3 The application guarantees message pairing and result attribution
The tool_calls[].id and the tool message’s tool_call_id must correspond one-to-one; this is a basic convention of Chat Completions-style APIs. The inference service generally won’t verify for you whether the pairing is complete or whether a result belongs to the current task; the client and orchestration layer must guarantee it themselves.
3.4 Session caching only marks reuse relationships, not conversation content
Some engines offer session-level caching: a request carries a session identifier, and the server reuses a previously seen identical prefix based on it. Note carefully that such an identifier is only a marker for a cache reference; it won’t automatically append or reconstruct the conversation context. Each request must still carry the full, intended prompt content. A cache hit only saves computation; it doesn’t change semantics. So you can’t assume that “passing a session ID means the server remembers what was said last turn.”
Also, coding agents execute local tools like reading and writing files and running commands, and they interact directly with the workspace. Regardless of which engine you choose, local tools should run inside a container or sandbox, with restricted access to directories and a whitelist for dangerous commands. Otherwise, no matter how thorough your business authorization is, it can’t prevent an accidental file deletion.
4. Core Example: Wiring Up a Complete Order Query
4.1 Call sequence
User: Where is order A100234?│▼(1) Model call #1 -- sends tool definitions│ ◀-- tool_calls: [{id: "call_order_a", name: "query_order_status", ...}]▼(2) App side: validate arguments -> authorize by user identity -> call business API (with trace_id)│▼(3) Model call #2 -- appends role=tool, tool_call_id="call_order_a"│ ◀-- "Order A100234 is in transit, expected to arrive tomorrow."▼Return to user
4.2 Key message shapes
First response (illustrative):
{"role": "assistant","content": null,"tool_calls": [{"id": "call_order_a","type": "function","function": {"name": "query_order_status","arguments": "{\"order_id\": \"A100234\"}"}}]}
Tool result message:
{"role": "tool","tool_call_id": "call_order_a","content": "{\"status\": \"IN_TRANSIT\", \"eta\": \"2026-09-07\"}"}
4.3 Reference code
The example below relies only on the standard library, so you can easily swap in any client compatible with this API style:
import jsonimport uuidimport urllib.requestfrom urllib.error import HTTPErrorENDPOINT = "http://127.0.0.1:8000/v1/chat/completions"MODEL = "local-coder"MAX_STEPS = 8TOOL_SCHEMA = {"type": "function","function": {"name": "query_order_status","description": "Look up order status by order ID (read-only)","parameters": {"type": "object","properties": {"order_id": {"type": "string", "pattern": "^[A-Z]\\d{6}$"}},"required": ["order_id"],},},}def post(payload: dict) -> dict:req = urllib.request.Request(ENDPOINT,data=json.dumps(payload).encode("utf-8"),headers={"Content-Type": "application/json"},)with urllib.request.urlopen(req, timeout=60) as resp:return json.loads(resp.read())def run_tool_loop(messages: list, task_id: str) -> str:"""Return the final answer; results are not reused across tasks; trace_id is tied to task_id."""for step in range(1, MAX_STEPS + 1):try:resp = post({"model": MODEL,"messages": messages,"tools": [TOOL_SCHEMA],"tool_choice": "auto",})except HTTPError as e:raise RuntimeError(f"Inference request failed with HTTP {e.code}, task_id={task_id}, step={step}") from emsg = resp["choices"][0]["message"]messages.append(msg)calls = msg.get("tool_calls") or []if not calls:return msg.get("content") or "" # finish_reason is stopfor call in calls:result = execute_checked(call, task_id) # validate -> authorize -> execute -> project resultmessages.append({"role": "tool","tool_call_id": call["id"], # must match the id that issued the call"content": json.dumps(result, ensure_ascii=False),})raise RuntimeError(f"Tool-call step limit exceeded, task_id={task_id}")
4.4 Six rules for accepting a result
Before a tool result goes back to the model, it should clear at least these six gates:
- Complete pairing: every
tool_calls[].idmust have exactly one correspondingtoolmessage with a matchingtool_call_id. With parallel calls, it’s easy to drop one or two, and the next request will be rejected. - Argument validation: validate the model-generated arguments field by field against the JSON Schema or against type, range, and enum constraints, and return the error as feedback on failure rather than executing directly. Treat user-supplied order IDs, paths, and commands as untrusted input.
- Failures get acknowledged too: timeouts, permission denials, and bad arguments should all be returned as a
toolmessage with a structured error, giving the model a chance to correct or to tell the user honestly. Silently skipping leaves the conversation stuck halfway. - Result projection: return only the fields needed to complete the task. Internal stack traces, database connection strings, secrets, and other users’ data are never passed down.
- Attribution check: include a task identifier in the request and confirm the call belongs to the current task before executing. After a task switch, results from the previous task can’t be carried into the new context.
- Idempotency and retries: write operations should carry an idempotency key. A timeout means “result unknown,” so query first before deciding whether to retry, to avoid duplicate execution.
5. Order Query vs. Refund: Same Loop, Different Responsibility Boundaries
Tool calls look the same, but the engineering constraints for an order query and a refund are completely different:
| Dimension | Order query (read-only) | Refund (write) |
|---|---|---|
| Side effects | None | Funds move, possibly irreversibly |
| Failure retries | Can retry automatically | First confirm whether it was already accepted, then decide whether to retry |
| Authorization | Verify order ownership and query permission | Verify operation permission; amount and payee account come from the business system, not the model |
| Model’s role | Decides and executes autonomously | Can only propose; requires the user’s second confirmation before execution |
| Acknowledgment content | Status and estimated delivery time | Acceptance ticket number and result, without internal transaction details |
| Audit | Standard logging | Full trace, traceable to the operator and approval records |
Mapping this to implementation:
- State in the tool description whether it’s “read-only, safe to execute automatically” or “involves a change of funds, requires user confirmation.”
- The refund arguments the model outputs are only a draft; the application reassembles and validates them before executing.
6. Authorization, Task Switching, and Observability
6.1 Authorization happens outside the model
A recommended decision order: identity authentication → tool whitelist (which tools the current user may call) → argument validation → data permission (does the order belong to this user) → execution and audit. If any step fails, the request doesn’t enter the model context. Otherwise, the model will leak out-of-scope information “without knowing it.”
6.2 Task-switching protection
A user changing the subject mid-task is the most common switching scenario for an agent. The orchestration layer should:
- Assign a unique ID to each task and track “whether there’s an unfinished tool call”;
- When switching tasks, invalidate the unfinished calls from the old task and don’t carry old results into the new one;
- If the user has already switched away while a tool is executing, write the result only to the old task’s record and don’t inject it into the current conversation.
6.3 Observability
The self-hosted chain is long, and a single failure could originate in the client, the gateway, the inference service, or a business API. Generate a trace_id that runs through the whole task, and record:
- Each round’s model call: TTFT, total time, and input/output token counts;
- Each tool call: duration, return code, and error code;
- Cache-hit status.
Logs of model inputs, tool arguments, and return results should all be redacted, keeping only the information needed to locate the problem.
7. Troubleshooting Quick Reference
| Symptom | Common cause | What to do |
|---|---|---|
Request rejected, error says the tool message lacks a match |
A parallel call missed an acknowledgment, or IDs don’t match | Fill in the missing ones by ID; don’t rewrite the IDs the server generated |
Model outputs only plain text, no tool_calls |
Tools aren’t enabled, the parsing config doesn’t match the model, or the prompt interferes | Check the inference service logs; verify the model’s tool-call format and parsing config |
| Tool arguments are incomplete in streaming output | In chunked returns, the id and name appear only in the first chunk, and arguments must be concatenated by index | Accumulate arguments by index, then execute once complete |
| The same tool executes twice | A retry after a network timeout, or the client processes a response twice | Add an idempotency key; on timeout, query before retrying |
| Context keeps growing until it reports “too long” or gets truncated | Multi-turn messages and tool results accumulate | Cap the number of steps; summarize or trim old tool results |
| Latency spikes and requests time out under high concurrency | Requests are queueing, or cache occupancy in memory is too high | Set queue and timeout limits; rate-limit or scale out when needed |
| Out-of-memory under concurrency | Long contexts consume too much cache | Cap max context length and concurrency |
| Returned results don’t match the request | The client points to the wrong service or model | Verify the client config, and assert the model identifier in the response |
8. Conclusion and Implementation Path
- Profile first, then select. Benchmark the two engine categories on the same terms based on shared-prefix ratio, request length, and latency sensitivity. Use data instead of impressions.
- Add engineering after integration. The inference service only generates. Pairing, authorization, attribution, and task switching must all be built solidly on the application side.
- Separate tool responsibilities. Read-only tools can be opened up for the model to use autonomously; write-operation tools must always include confirmation and idempotency.
- Leverage cloud capabilities. If the team lacks inference-operations experience, or traffic fluctuates significantly and you need fast validation, you can also evaluate compute and model-serving products on Baidu AI Cloud. Hand deployment and operations to the platform and let the team focus on orchestration, authorization, and business integration. If you self-host, prefer a mainstream solution with a compatible API to reduce client-side rework.
Treat engine selection as a capacity problem and tool calling as a security problem, and a self-hosted model can be both fast and reliably integrated.
