LLM Function Calling on a $110/mo Server: How We Scaled a Nigerian Loan Agent with vLLM and Qdrant
Faced with a $4,350/month OpenAI bill for a WhatsApp loan resolution agent, we replaced cloud LLM APIs with quantized Llama 3.1 8B on vLLM and Qdrant hybrid search. Here is how we reduced latency to 480ms and cut infrastructure spend to $310/month without sacrificing schema precision.
A mid-sized digital lending platform in Lagos came to Neobot Tech with a scaling roadblock. Their WhatsApp customer support agent—designed to resolve loan repayment disputes, check NIP transfer statuses, and process grace period requests—was draining cash. Every incoming customer query triggered a multi-turn agent loop powered directly by OpenAI’s GPT-4o API.
At 18,000 monthly active users and an average of 6 message turns per conversation, their monthly OpenAI bill reached $4,350. In a business where loan margins are paper-thin and customer fees are denominated in Naira, paying a variable, USD-denominated software bill to OpenAI was untenable. Worse, API round-trip latencies frequently spiked above 3.5 seconds during peak West Africa hours (2 PM – 6 PM WAT). These delays caused WhatsApp webhook timeouts, which triggered retries and resulted in duplicate, hallucinated agent execution loops.
We replaced their cloud API stack with a self-hosted, quantized local model pipeline running on bare-metal GPU infrastructure. This case study details how we designed the system, the trade-offs we navigated, and how to replicate the playbook.
System Constraints & Local Context
Building AI agents for West African financial services presents operational constraints that off-the-shelf tutorial architectures ignore:
- FX Volatility and Margin Preservation: Paying USD per token against Naira revenue creates unpredictable operating expenses. The client needed a fixed monthly infrastructure cost ceiling regardless of message volume spikes.
- Code-Switching and Non-Standard Input: Customers routinely write in a blend of formal English, Nigerian Pidgin, and local slang ("I don transfer the money since morning, alert never drop"). Traditional small models often fail to parse intent when queries deviate from standardized English.
- Zero Tolerance for Tool-Calling Syntax Failure: The agent must execute real ledger commands (
query_nip_ledger,apply_grace_period). A malformed JSON response or hallucinated parameter directly mutates core database records or fails downstream banking jobs. - Strict Webhook Latency Limits: WhatsApp Business API webhooks require an HTTP 200 response within 15 seconds, but customer drop-off increases sharply if the initial response token takes more than 1 second to arrive.
What Was Tried (and Failed)
Before landing on the production design, we evaluated two conventional optimization strategies. Both fell short under real-world traffic.
Attempt 1: Standardizing on OpenAI GPT-3.5-Turbo
We initially attempted to lower costs by swapping GPT-4o for GPT-3.5-Turbo while retaining OpenAI infrastructure. Token costs dropped by 70%, but tool-calling reliability degraded significantly.
When presented with non-standard Nigerian English input, GPT-3.5-Turbo's JSON output failed structural validation 6.8% of the time. It frequently output invalid schema parameters (e.g., passing a 10-digit NUBAN account number as a string with spaces or hallucinating non-existent parameters like loan_id="unknown"). Retrying malformed calls erased the latency savings and added hidden token costs.
Attempt 2: Managed Deployment of Llama-3.1-70B on AWS SageMaker
Next, we deployed an unquantized Llama-3.1-70B-Instruct model on an AWS SageMaker ml.g5.12xlarge instance. While inference accuracy and code-switching comprehension matched GPT-4o, the infrastructure costs remained high ($1,450/month for the instance alone). Cold starts during auto-scaling introduced 12-second latency spikes. As detailed in our analysis on Replacing AWS EKS with Nomad and WireGuard on Hetzner, managed cloud GPU infrastructure in AWS carries significant markup compared to bare-metal alternatives.
| Architecture | Monthly Cost (USD) | P95 Time-To-First-Token | Tool-Call Schema Error Rate | FX Exposure | | :--- | :--- | :--- | :--- | :--- | | OpenAI GPT-4o API | $4,350 | 2,850 ms | 0.2% | High (Variable USD) | | OpenAI GPT-3.5-Turbo | $890 | 1,120 ms | 6.8% | High (Variable USD) | | Llama 3.1 70B (AWS SageMaker) | $1,450 | 3,400 ms | 1.1% | Medium (Fixed USD) | | Llama 3.1 8B AWQ + vLLM + Qdrant (Final) | $310 | 480 ms | 0.0% | Fixed Low USD |
The Production Architecture
The final solution combines a multi-tier routing architecture with open-weights models served on specialized inference engines.

1. Semantic Pre-Router in Go
Not every customer message requires an LLM generation. We built a lightweight microservice in Go that sits directly behind the WhatsApp webhook gateway.
Incoming messages pass through an exact-match cache and a fast vector similarity classifier using a lightweight embedding model (BAAI/bge-small-en-v1.5). If a query matches common static requests (e.g., "Where is your physical office?", "What are your interest rates?"), the router immediately responds with pre-approved static content in under 15ms, bypassing the LLM pipeline entirely. This reduced token generation volume by 34%.
For non-static transactional queries, the Go service ensures idempotency before triggering the LLM, following patterns similar to those we use when handling high-volume webhooks with Redis and Postgres.
2. Hybrid Vector Search with Qdrant
When context retrieval is necessary, simple dense vector search fails on local African banking terminology. For example, search queries containing terms like "NIP ghost debit", "Paystack transaction reference", or specific bank acronyms ("GTB", "Kuda") often produce poor semantic density scores with standard dense embeddings.
We implemented Qdrant Hybrid Search, combining dense vector embeddings (BAAI/bge-m3) with sparse vector BM25 keyword matching. Dense vectors capture overall intent ("I paid but my account is not updated"), while sparse vectors preserve key identifiers like payment gateway references and bank codes.
3. vLLM Engine with Outlines / Guided JSON Decoding
To serve the core agent, we selected casperhansen/llama-3.1-8b-instruct-awq—a 4-bit quantized version of Meta's Llama 3.1 8B model. We hosted the model using vLLM on a single dedicated Hetzner GPU server featuring an NVIDIA RTX 4090 (24GB VRAM) running on Linux.
vLLM's PagedAttention engine manages KV-cache memory efficiently, allowing us to serve up to 35 concurrent generation streams without exhausting VRAM.
To eliminate JSON parsing failures during tool calls, we leveraged vLLM's structured output decoding feature (guided_json). By feeding Pydantic-defined JSON schemas directly into the vLLM engine at runtime, the generation logits are constrained at the token level. The model is physically incapable of generating a character that breaks the schema structure, bringing schema parsing errors to exactly 0.0%.
Implementation Guide: Building the Inference Engine
Here is how to configure the production components.
Step 1: Deploying vLLM with AWQ Quantization
Deploy the vLLM server with explicit memory allocations and model parameters tuned for low-latency batching:
python3 -m vllm.entrypoints.openai.api_server \
--model casperhansen/llama-3.1-8b-instruct-awq \
--quantization awq \
--dtype float16 \
--gpu-memory-utilization 0.90 \
--max-model-len 4096 \
--port 8000 \
--enforce-eager
Setting --gpu-memory-utilization 0.90 allocates 90% of the 24GB VRAM to model weights and KV-cache, leaving sufficient room for execution context without running into out-of-memory (OOM) faults.
Step 2: Enforcing Structured Tool Calling in Python
When executing tool calls from your backend agent service, pass your Pydantic schema using the OpenAI-compatible vLLM client endpoint:
import json
from openai import OpenAI
from pydantic import BaseModel, Field
# Initialize OpenAI client pointing to the self-hosted vLLM endpoint
client = OpenAI(
base_url="http://127.0.0.1:8000/v1",
api_key="token-not-required-for-internal-mesh"
)
# Define the exact tool schema using Pydantic
class NIPDisputeToolCall(BaseModel):
nuban_account: str = Field(..., description="10-digit Nigerian NUBAN account number")
bank_code: str = Field(..., description="3-digit NIBSS bank code or identifier")
transaction_amount: float = Field(..., description="Claimed transfer amount in NGN")
transaction_date: str = Field(..., description="ISO-8601 formatted transaction date")
schema_dict = NIPDisputeToolCall.model_json_schema()
def extract_dispute_parameters(user_message: str) -> NIPDisputeToolCall:
system_prompt = (
"You are an automated loan customer support extraction engine. "
"Extract transaction dispute parameters accurately from user text."
)
# Utilize vLLM guided_json parameter via extra_body
response = client.chat.completions.create(
model="casperhansen/llama-3.1-8b-instruct-awq",
messages=[
{"role": "system", "content": system_prompt},
{"role": "user", "content": user_message}
],
temperature=0.0,
extra_body={
"guided_json": schema_dict
}
)
raw_json = response.choices[0].message.content
# Guaranteed to parse successfully due to logit-level schema enforcement
return NIPDisputeToolCall.model_validate_json(raw_json)
# Example usage with local code-switching input
input_text = "I sent 45000 naira from my GTB account 0123456789 yesterday night but the loan balance never change."
extracted_data = extract_dispute_parameters(input_text)
print(extracted_data.model_dump_json(indent=2))
Step 3: Reliable Downstream Processing
Once parameters are reliably extracted by the LLM layer, pass them to your core ledger services via an asynchronous queue. In critical financial environments, direct API-to-API HTTP calls risk state desynchronization if the downstream ledger engine experiences a temporary outage. To ensure zero loss of transaction adjustments, we feed extracted parameters directly into a transactional processing engine, as discussed in our guide on ditching Celery for a Go Transactional Outbox Engine.
Quantitative Results & Impact
After running the self-hosted AI engine in production for 90 days, the platform achieved the following benchmarks:
- Cost Reduction: Total monthly infrastructure spend dropped from $4,350 to $310 ($110/mo for Hetzner Dedicated GPU, $120/mo for high-availability Qdrant cluster, $80/mo for bare-metal app hosts). This represents an 82.8% net reduction in AI operational cost.
- Latency Improvements: Time-to-first-token (TTFT) dropped from an average of 2,850ms to 480ms. Complete message execution cycles now average under 1.2 seconds, well within WhatsApp's webhook limits.
- Parsing Reliability: Structured decoding completely eliminated malformed JSON payload errors. Schema-validation error rates went from 6.8% (on GPT-3.5-Turbo) to 0.0%.
Key Takeaways for Technical Founders
- Stop defaulting to cloud APIs for structured tool calling: If your agent workflow relies heavily on predefined JSON outputs rather than creative writing, open-weights models (like Llama 3.1 8B or DeepSeek-R1-Distill variants) coupled with grammar-constrained decoding (vLLM/Outlines) perform consistently better than unconstrained cloud APIs, at a fraction of the cost.
- Optimize your retrieval stack before your model size: Switching from basic dense embeddings to Qdrant hybrid search yielded larger comprehension improvements for local domain terms than upgrading from an 8B model to a 70B model.
- Use pre-LLM semantic routing: Filtering static queries upstream before they reach GPU memory is the easiest way to immediately reduce inference loads.
Neobot Engineering Standard
Every system deployed by Neobot Tech incorporates enterprise baseline practices. We continuously audit our database topologies, REST API query paths, and frontend modular bundles to prevent latency spikes and ensure top-tier security posture.
Discussion
Comments Coming Soon
We are currently migrating our discussion engine to a new real-time database schema. Check back shortly to join the conversation.