Published
LLM API Integration: Production Best Practices for Enterprise Systems
Run LLM APIs in production: provider abstraction, streaming, retries with backoff, rate limits, caching, token management, monitoring and API key security.
- Written by
- Ali ÖzdurmuşFounder, Veni AI
- Updated
- Reading time
- 7 min read

Calling an LLM API in a prototype takes five lines. Running it inside an ERP workflow or a customer-facing app, with rate limits, outages, cost limits and audits, takes considerably more. This guide covers the production patterns we rely on.
Code samples are illustrative Python.
clientis an initialized SDK client andMODELis a placeholder for the model ID you choose.
Choosing Providers
The main hosted model families as of October 2026 (from our model catalog):
| Provider | Current models | API |
|---|---|---|
| OpenAI | GPT-6 Astra, GPT-6 Luna, GPT-6.1 Sol | https://api.openai.com/v1/... |
| Anthropic | Claude Opus 5.5, Claude Sonnet 5.5, Claude Haiku 5.5 | https://api.anthropic.com/v1/messages |
| Gemini 4 Argon, Gemini 3.8 Flash | Gemini API / Vertex AI | |
| Open weights | DeepSeek V4, Kimi K3, Mistral Medium 3.5 and others | Hosted endpoints or your own servers |
All of them support tool calling, structured output and image input in some form, and most offer streaming, batch processing and prompt caching. Differences that matter in practice: data processing terms and regions, rate limits for your account tier, price per task and quality on your own evaluation set.
Design for switching: wrap providers behind one internal interface so you can change models per task without touching business logic.
Basic Integration Structure
OpenAI Python SDK
import os
from openai import OpenAI
client = OpenAI(api_key=os.environ["OPENAI_API_KEY"])
MODEL = "your-model-id"
response = client.chat.completions.create(
model=MODEL,
messages=[
{"role": "system", "content": "You are a helpful assistant."},
{"role": "user", "content": "Hello!"}
],
temperature=0.7,
max_tokens=1000
)
print(response.choices[0].message.content)Anthropic Python SDK
from anthropic import Anthropic
client = Anthropic(api_key=os.environ["ANTHROPIC_API_KEY"])
message = client.messages.create(
model=MODEL,
max_tokens=1024,
messages=[
{"role": "user", "content": "Hello!"}
]
)
print(message.content[0].text)Streaming Response
# OpenAI Streaming
stream = client.chat.completions.create(
model=MODEL,
messages=[{"role": "user", "content": "Tell me a long story"}],
stream=True
)
for chunk in stream:
if chunk.choices[0].delta.content:
print(chunk.choices[0].delta.content, end="")Error Handling
Error Types
| Error Code | Description | Solution |
|---|---|---|
| 400 | Invalid request | Check request format |
| 401 | Invalid API key | Verify API key |
| 429 | Rate limit | Retry with backoff |
| 500 | Server error | Retry with exponential backoff |
| 503 | Service unavailable | Wait and retry |
Robust Error Handling
import time
from openai import RateLimitError, APIError, APIConnectionError
def call_llm_with_retry(messages, max_retries=3):
for attempt in range(max_retries):
try:
response = client.chat.completions.create(
model=MODEL,
messages=messages
)
return response.choices[0].message.content
except RateLimitError:
wait_time = 2 ** attempt # Exponential backoff
print(f"Rate limited. Waiting {wait_time}s...")
time.sleep(wait_time)
except APIConnectionError:
print("Connection error. Retrying...")
time.sleep(1)
except APIError as e:
print(f"API error: {e}")
if attempt == max_retries - 1:
raise
raise Exception("Max retries exceeded")Exponential Backoff with Jitter
import random
def exponential_backoff(attempt, base=1, max_wait=60):
wait = min(base * (2 ** attempt), max_wait)
jitter = random.uniform(0, wait * 0.1)
return wait + jitterRate Limiting Management
Rate Limit Types
- RPM (Requests Per Minute): Number of requests per minute
- TPM (Tokens Per Minute): Number of tokens per minute
- RPD (Requests Per Day): Number of requests per day
Token Bucket Algorithm
import time
from threading import Lock
class TokenBucket:
def __init__(self, tokens_per_second, max_tokens):
self.tokens_per_second = tokens_per_second
self.max_tokens = max_tokens
self.tokens = max_tokens
self.last_update = time.time()
self.lock = Lock()
def acquire(self, tokens=1):
with self.lock:
now = time.time()
elapsed = now - self.last_update
self.tokens = min(
self.max_tokens,
self.tokens + elapsed * self.tokens_per_second
)
self.last_update = now
if self.tokens >= tokens:
self.tokens -= tokens
return True
return False
def wait_and_acquire(self, tokens=1):
while not self.acquire(tokens):
time.sleep(0.1)
# Usage
rate_limiter = TokenBucket(tokens_per_second=10, max_tokens=100)
rate_limiter.wait_and_acquire()
# API call...Caching Strategies
Response Caching
import hashlib
import json
from functools import lru_cache
import redis
redis_client = redis.Redis(host='localhost', port=6379, db=0)
def get_cache_key(messages, model, temperature):
content = json.dumps({
"messages": messages,
"model": model,
"temperature": temperature
}, sort_keys=True)
return hashlib.md5(content.encode()).hexdigest()
def cached_llm_call(messages, model=MODEL, temperature=0.7, ttl=3600):
cache_key = get_cache_key(messages, model, temperature)
# Check cache
cached = redis_client.get(cache_key)
if cached:
return json.loads(cached)
# API call
response = client.chat.completions.create(
model=model,
messages=messages,
temperature=temperature
)
result = response.choices[0].message.content
# Save to cache
redis_client.setex(cache_key, ttl, json.dumps(result))
return resultSemantic Caching
Serve similar queries from cache:
def semantic_cache_lookup(query, threshold=0.95):
query_embedding = get_embedding(query)
# Search similar query in Vector DB
results = vector_db.search(
vector=query_embedding,
top_k=1,
filter={"type": "cache"}
)
if results and results[0].score >= threshold:
return results[0].metadata["response"]
return NoneToken Management
Token Counting
import tiktoken
# Token counts differ between providers; use each provider's token-counting
# endpoint when you need exact numbers. tiktoken gives a good estimate.
def count_tokens(text, encoding_name="o200k_base"):
encoding = tiktoken.get_encoding(encoding_name)
return len(encoding.encode(text))
def count_message_tokens(messages, encoding_name="o200k_base"):
encoding = tiktoken.get_encoding(encoding_name)
tokens = 0
for message in messages:
tokens += 4 # message overhead
for key, value in message.items():
tokens += len(encoding.encode(value))
tokens += 2 # reply overhead
return tokensContext Window Management
def truncate_messages(messages, max_tokens=4000):
total_tokens = count_message_tokens(messages)
while total_tokens > max_tokens and len(messages) > 2:
# Preserve System message, delete oldest user/assistant
messages.pop(1)
total_tokens = count_message_tokens(messages)
return messagesAsync Operations
Async Client
import asyncio
from openai import AsyncOpenAI
async_client = AsyncOpenAI(api_key=os.environ["OPENAI_API_KEY"])
async def async_llm_call(prompt):
response = await async_client.chat.completions.create(
model=MODEL,
messages=[{"role": "user", "content": prompt}]
)
return response.choices[0].message.content
async def batch_process(prompts):
tasks = [async_llm_call(p) for p in prompts]
results = await asyncio.gather(*tasks)
return results
# Usage
prompts = ["Question 1", "Question 2", "Question 3"]
results = asyncio.run(batch_process(prompts))Concurrent Rate-Limited Requests
import asyncio
from asyncio import Semaphore
async def rate_limited_call(semaphore, prompt):
async with semaphore:
response = await async_client.chat.completions.create(
model=MODEL,
messages=[{"role": "user", "content": prompt}]
)
return response.choices[0].message.content
async def batch_with_rate_limit(prompts, max_concurrent=5):
semaphore = Semaphore(max_concurrent)
tasks = [rate_limited_call(semaphore, p) for p in prompts]
return await asyncio.gather(*tasks)Monitoring and Logging
Request Logging
import logging
import time
from functools import wraps
logging.basicConfig(level=logging.INFO)
logger = logging.getLogger(__name__)
def log_llm_call(func):
@wraps(func)
def wrapper(*args, **kwargs):
start_time = time.time()
try:
result = func(*args, **kwargs)
duration = time.time() - start_time
logger.info(f"LLM Call Success", extra={
"duration": duration,
"model": kwargs.get("model"),
"tokens_used": result.usage.total_tokens
})
return result
except Exception as e:
duration = time.time() - start_time
logger.error(f"LLM Call Failed", extra={
"duration": duration,
"error": str(e)
})
raise
return wrapperMetrics Collection
from prometheus_client import Counter, Histogram
llm_requests_total = Counter(
'llm_requests_total',
'Total LLM API requests',
['model', 'status']
)
llm_latency = Histogram(
'llm_request_latency_seconds',
'LLM request latency',
['model']
)
llm_tokens = Counter(
'llm_tokens_total',
'Total tokens used',
['model', 'type'] # input, output
)Security Best Practices
API Key Management
import os
from dotenv import load_dotenv
load_dotenv()
# Get from Environment variable
api_key = os.getenv("OPENAI_API_KEY")
# Never hardcode!
# ❌ api_key = "sk-..."Input Validation
def validate_input(text, max_length=10000):
if not text or not isinstance(text, str):
raise ValueError("Invalid input")
if len(text) > max_length:
raise ValueError(f"Input too long: {len(text)} > {max_length}")
# Injection check
dangerous_patterns = ["<script>", "{{", "{%"]
for pattern in dangerous_patterns:
if pattern in text.lower():
raise ValueError("Potentially dangerous input")
return text.strip()Output Sanitization
import html
def sanitize_output(text):
# HTML escape
text = html.escape(text)
# PII masking
text = mask_pii(text)
return textProduction Architecture
┌──────────────┐ ┌──────────────┐ ┌──────────────┐
│ Client │────▶│ API GW │────▶│ LLM Service │
└──────────────┘ │ (Rate Limit)│ └──────┬───────┘
└──────────────┘ │
┌─────▼─────┐
┌──────────────┐ │ Router │
│ Cache │◀───▶│ │
│ (Redis) │ └─────┬─────┘
└──────────────┘ │
┌──────────────────┼──────────────────┐
│ │ │
┌──────▼──────┐ ┌─────▼─────┐ ┌──────▼──────┐
│ OpenAI │ │ Anthropic │ │ Google │
└─────────────┘ └───────────┘ └─────────────┘Conclusion
A production LLM integration is ordinary backend engineering done carefully: one interface over several providers, retries with backoff, rate limiting, caching, token budgets, monitoring and secure key handling. Get these right once and every AI feature you add later inherits them.
Veni AI integrates AI into companies' existing software, from ERP and CRM to internal portals, with the reliability and security those systems need. See our services or talk to our engineers.


