发布于

LLM API集成:企业系统的生产最佳实践

在生产环境稳定运行LLM API:多供应商抽象、流式输出、带退避的重试、限流、响应缓存、Token管理、监控告警与API密钥安全的完整实践。

作者
Ali ÖzdurmuşVeni AI 创始人
更新于
阅读时间
阅读约 6 分钟

在原型中调用LLM API只需五行代码。而要让它在ERP工作流或面向客户的应用中运行,并应对限流、故障、成本上限和审计,则要复杂得多。本指南介绍我们在生产中依赖的各种模式。

代码示例为示意性的Python。client是已初始化的SDK客户端,MODEL是您所选模型ID的占位符。

选择供应商

截至2026年10月,主要的托管模型家族如下(来自我们的模型目录):

供应商当前模型API
OpenAIGPT-6 Astra、GPT-6 Luna、GPT-6.1 Solhttps://api.openai.com/v1/...
AnthropicClaude Opus 5.5、Claude Sonnet 5.5、Claude Haiku 5.5https://api.anthropic.com/v1/messages
GoogleGemini 4 Argon、Gemini 3.8 FlashGemini API / Vertex AI
开放权重DeepSeek V4、Kimi K3、Mistral Medium 3.5等托管端点或您自己的服务器

它们都以某种形式支持工具调用、结构化输出和图像输入,大多数还提供流式输出、批处理和提示词缓存。实践中真正重要的差异包括:数据处理条款和区域、您账户等级的限流额度、单任务价格,以及在您自己的评估集上的质量。

为切换而设计:把各供应商封装在同一个内部接口之后,这样就能按任务更换模型,而无需改动业务逻辑。

基础集成结构

OpenAI Python SDK

python
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

python
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)

流式响应

python
# 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="")

错误处理

错误类型

错误码描述解决办法
400无效请求检查请求格式
401API密钥无效核实API密钥
429触发限流退避后重试
500服务器错误指数退避重试
503服务不可用等待后重试

稳健的错误处理

python
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")

带抖动的指数退避

python
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 + jitter

限流管理

限流类型

  • RPM(每分钟请求数): 每分钟的请求数量
  • TPM(每分钟Token数): 每分钟的Token数量
  • RPD(每日请求数): 每天的请求数量

令牌桶算法

python
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...

缓存策略

响应缓存

python
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 result

语义缓存

用缓存响应相似的查询:

python
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 None

Token管理

Token计数

python
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 tokens

上下文窗口管理

python
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 messages

异步操作

异步客户端

python
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))

受限流约束的并发请求

python
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)

监控与日志

请求日志

python
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 wrapper

指标采集

python
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
)

安全最佳实践

API密钥管理

python
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-..."

输入校验

python
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()

输出清洗

python
import html

def sanitize_output(text):
    # HTML escape
    text = html.escape(text)
    
    # PII masking
    text = mask_pii(text)
    
    return text

生产架构

┌──────────────┐     ┌──────────────┐     ┌──────────────┐
│   Client     │────▶│   API GW     │────▶│  LLM Service │
└──────────────┘     │  (Rate Limit)│     └──────┬───────┘
                     └──────────────┘            │
                                          ┌─────▼─────┐
                     ┌──────────────┐     │  Router   │
                     │    Cache     │◀───▶│           │
                     │   (Redis)    │     └─────┬─────┘
                     └──────────────┘           │
                            ┌──────────────────┼──────────────────┐
                            │                  │                  │
                     ┌──────▼──────┐    ┌─────▼─────┐    ┌──────▼──────┐
                     │   OpenAI    │    │ Anthropic │    │   Google    │
                     └─────────────┘    └───────────┘    └─────────────┘

结论

生产级的LLM集成就是认真做好的常规后端工程:在多个供应商之上提供统一接口、带退避的重试、限流、缓存、Token预算、监控以及安全的密钥处理。把这些一次做对,之后新增的每个AI功能都能直接继承。

Veni AI将AI集成到企业现有的软件中,从ERP、CRM到内部门户,并提供这些系统所需的可靠性与安全性。查看我们的服务,或联系我们的工程师。

继续阅读

有流程适合交给 AI 来跑吗?

描述一个目前的流程,我们会告诉您 AI 应用或智能体可以承担其中哪些重复性步骤。