بوابات LLM والتوجيه

LiteLLM: بوابة LLM الموحدة

4 دقيقة للقراءة

LiteLLM هي بوابة LLM الرائدة مفتوحة المصدر، توفر واجهة موحدة متوافقة مع OpenAI لأكثر من 100 مزود LLM. في 2025، قدمت LiteLLM بوابة الوكيل (A2A - وكيل إلى وكيل) لاتصال الوكلاء البيني وحققت 8ms P95 زمن استجابة عند 1,000 طلب في الثانية.

الميزات الأساسية

┌─────────────────────────────────────────────────────────────┐
│                     بوابة LiteLLM                           │
├─────────────────────────────────────────────────────────────┤
│                                                             │
│  API الموحد                                                 │
│  ┌─────────────────────────────────────────────────────┐   │
│  │  /v1/chat/completions   → جميع نماذج الدردشة       │   │
│  │  /v1/embeddings         → جميع نماذج التضمين       │   │
│  │  /v1/images/generations → نماذج الصور              │   │
│  │  /v1/audio/transcriptions → نماذج الكلام           │   │
│  │  /v1/search             → البحث الموحد (2025)      │   │
│  └─────────────────────────────────────────────────────┘   │
│                                                             │
│  100+ مزود مدعوم:                                          │
│  OpenAI، Anthropic، Azure، AWS Bedrock، Google Vertex،    │
│  Cohere، Together، Replicate، Ollama، vLLM، والمزيد...    │
│                                                             │
└─────────────────────────────────────────────────────────────┘

البداية السريعة

التثبيت

pip install litellm

# أو مع خادم الوكيل
pip install 'litellm[proxy]'

استخدام SDK

from litellm import completion

# OpenAI
response = completion(
    model="gpt-4o",
    messages=[{"role": "user", "content": "مرحباً!"}]
)

# Anthropic - نفس الواجهة
response = completion(
    model="claude-sonnet-4-20250514",
    messages=[{"role": "user", "content": "مرحباً!"}]
)

# Azure OpenAI
response = completion(
    model="azure/gpt-4o",
    messages=[{"role": "user", "content": "مرحباً!"}],
    api_base="https://your-resource.openai.azure.com",
    api_key="your-azure-key"
)

# AWS Bedrock
response = completion(
    model="bedrock/anthropic.claude-3-sonnet-20240229-v1:0",
    messages=[{"role": "user", "content": "مرحباً!"}]
)

# Ollama المحلي
response = completion(
    model="ollama/llama3.2",
    messages=[{"role": "user", "content": "مرحباً!"}],
    api_base="http://localhost:11434"
)

الدعم غير المتزامن

import asyncio
from litellm import acompletion

async def generate_responses():
    tasks = [
        acompletion(model="gpt-4o", messages=[{"role": "user", "content": f"سؤال {i}"}])
        for i in range(10)
    ]
    responses = await asyncio.gather(*tasks)
    return responses

نشر خادم الوكيل

التكوين

# litellm_config.yaml
model_list:
  - model_name: gpt-4o
    litellm_params:
      model: openai/gpt-4o
      api_key: os.environ/OPENAI_API_KEY

  - model_name: claude-sonnet
    litellm_params:
      model: anthropic/claude-sonnet-4-20250514
      api_key: os.environ/ANTHROPIC_API_KEY

  - model_name: gpt-4o
    litellm_params:
      model: azure/gpt-4o-deployment
      api_base: os.environ/AZURE_API_BASE
      api_key: os.environ/AZURE_API_KEY

# تكوين الاحتياطي
router_settings:
  routing_strategy: "latency-based"
  retry_policy:
    num_retries: 3
    fallbacks: ["gpt-4o", "claude-sonnet"]

# إدارة الميزانية
litellm_settings:
  max_budget: 1000  # دولار في الشهر
  budget_duration: monthly

تشغيل الوكيل

# بدء خادم الوكيل
litellm --config litellm_config.yaml --port 4000

# أو مع Docker
docker run -p 4000:4000 \
  -v $(pwd)/litellm_config.yaml:/app/config.yaml \
  -e OPENAI_API_KEY=$OPENAI_API_KEY \
  ghcr.io/berriai/litellm:main-latest \
  --config /app/config.yaml

استخدام الوكيل

from openai import OpenAI

# التوجيه لوكيل LiteLLM
client = OpenAI(
    base_url="http://localhost:4000/v1",
    api_key="your-litellm-key"
)

# استخدم أي نموذج مكوّن
response = client.chat.completions.create(
    model="gpt-4o",  # يُوجه بواسطة LiteLLM
    messages=[{"role": "user", "content": "مرحباً!"}]
)

استراتيجيات توجيه النماذج

التوجيه القائم على زمن الاستجابة

router_settings:
  routing_strategy: "latency-based"
  # التوجيه للنشر الأقل زمن استجابة

التوجيه القائم على التكلفة

router_settings:
  routing_strategy: "cost-based"
  # التوجيه للخيار الأرخص المتاح

موازنة الحمل

model_list:
  # نشر متعدد لنفس النموذج
  - model_name: gpt-4o
    litellm_params:
      model: openai/gpt-4o
      rpm: 1000  # حد المعدل
    model_info:
      weight: 0.5

  - model_name: gpt-4o
    litellm_params:
      model: azure/gpt-4o
      rpm: 2000
    model_info:
      weight: 0.5

بوابة الوكيل (بروتوكول A2A)

بوابة الوكيل تمكّن اتصال وكيل إلى وكيل مع بروتوكولات موحدة:

from litellm import Agent, AgentGateway

# تعريف وكيل
class ResearchAgent(Agent):
    name = "research_agent"
    description = "يبحث في المواضيع ويقدم ملخصات"

    async def process(self, query: str) -> str:
        response = await acompletion(
            model="gpt-4o",
            messages=[
                {"role": "system", "content": "أنت مساعد بحث."},
                {"role": "user", "content": query}
            ]
        )
        return response.choices[0].message.content

# التسجيل مع البوابة
gateway = AgentGateway()
gateway.register(ResearchAgent())

# الوكلاء الآخرون يمكنهم الاكتشاف والاستدعاء
result = await gateway.call(
    agent="research_agent",
    query="ما هي أحدث التطورات في الحوسبة الكمومية؟"
)

المفاتيح الافتراضية وإدارة الفرق

# ميزانية ووصول لكل فريق
general_settings:
  master_key: "sk-master-key"

team_settings:
  - team_id: "engineering"
    max_budget: 500
    models: ["gpt-4o", "claude-sonnet"]

  - team_id: "data-science"
    max_budget: 1000
    models: ["gpt-4o", "claude-sonnet", "embedding-*"]
# توليد مفاتيح خاصة بالفريق
import requests

response = requests.post(
    "http://localhost:4000/key/generate",
    json={
        "team_id": "engineering",
        "key_alias": "eng-dev-key",
        "max_budget": 100,
        "duration": "30d"
    },
    headers={"Authorization": "Bearer sk-master-key"}
)

نشر Kubernetes

apiVersion: apps/v1
kind: Deployment
metadata:
  name: litellm-proxy
spec:
  replicas: 3
  selector:
    matchLabels:
      app: litellm
  template:
    metadata:
      labels:
        app: litellm
    spec:
      containers:
        - name: litellm
          image: ghcr.io/berriai/litellm:main-latest
          ports:
            - containerPort: 4000
          env:
            - name: OPENAI_API_KEY
              valueFrom:
                secretKeyRef:
                  name: llm-secrets
                  key: openai-key
          volumeMounts:
            - name: config
              mountPath: /app/config.yaml
              subPath: config.yaml
      volumes:
        - name: config
          configMap:
            name: litellm-config
---
apiVersion: v1
kind: Service
metadata:
  name: litellm
spec:
  selector:
    app: litellm
  ports:
    - port: 4000
      targetPort: 4000

معايير الأداء (2025)

المقياس القيمة
P50 زمن الاستجابة 3ms
P95 زمن الاستجابة 8ms
P99 زمن الاستجابة 15ms
الإنتاجية 1,000+ طلب/ث لكل نسخة
الذاكرة ~200MB أساسي
:::

اختبار

الوحدة 5: بوابات LLM والتوجيه

خذ الاختبار