Ypeng12 commited on
Commit
7a41111
·
1 Parent(s): d142175

docs & chore: rename project to InferRoute, clean up legacy edgeserve directory

Browse files
InferRoute 项目规划报告(LLM 推理网关与控制平面).pdf ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:8f5c73ebba4a9a69beae572bc02d623363a840830a053549bb13b7ef3b428786
3
+ size 888918
deep-research-report.md CHANGED
@@ -1,8 +1,8 @@
1
- # EdgeServe AI 生产级低延迟 LLM 推理路由与可观测平台设计报告
2
 
3
  ## 执行摘要
4
 
5
- EdgeServe AI 的最佳作品集定位,不是“又一个 AI 聊天壳”,而是一个**面向生产流量的低延迟 LLM Gateway**:它统一接入本地推理引擎与云模型 API,在请求进入后完成鉴权、限流、意图识别、路由决策、缓存命中、流式返回、失败回退、成本归集与端到端可观测。这类项目能同时覆盖 Amazon/Google 偏好的分布式系统、SRE/可观测、API 设计与弹性扩缩,也能覆盖 NVIDIA/Tesla 更看重的推理后端、GPU 调度、量化和吞吐/延迟基准。官方资料表明,vLLM 已提供 OpenAI 兼容服务、前缀缓存、Prometheus 指标与分布式 tensor/pipeline parallel;Ray Serve LLM 则强调多节点推理、自动扩缩、自定义路由与 Grafana 仪表盘;Kubernetes 原生支持 HPA、多指标扩缩与设备插件;OpenTelemetry Collector、Prometheus、Grafana、Jaeger 形成一条标准化、供应商无关的观测链路。citeturn17search9turn18search0turn1search0turn1search1turn0search2turn13search0turn22search2turn23search1turn10search2
6
 
7
  如果只做作品集版本,最推荐的技术路径是:**FastAPI/Starlette API Gateway + 自研 Router/Scheduler + Redis 缓存/队列 + Postgres/pgvector 元数据层 + vLLM 本地 GPU 推理 + OpenAI/Anthropic/Vertex/Azure 适配器 + Prometheus/Grafana/Jaeger**。原因很直接:FastAPI/Starlette 适合快速产出异步 HTTP 和流式响应;Redis 既适合全局限流,也适合消费者组与异步队列;Postgres 可做审计、账单、请求日志与配置,pgvector 可做语义缓存或路由辅助;vLLM 对本地部署最友好,Triton 更适合多框架、动态批处理和 NIM 风格生产环境,ONNX Runtime 更适合边缘与 CPU/轻量 GPU 场景。citeturn16search0turn14search0turn12search0turn12search6turn11search1turn17search9turn18search0turn0search7turn0search1turn19search0turn19search1
8
 
@@ -10,7 +10,7 @@ EdgeServe AI 的最佳作品集定位,不是“又一个 AI 聊天壳”,而
10
 
11
  ## 产品目标与系统边界
12
 
13
- EdgeServe AI 的目标用户不应泛泛定义为“所有 LLM 开发者”,而应明确到三类:
14
 
15
  | 目标用户 | 核心诉求 | 对应价值 |
16
  |---|---|---|
@@ -28,7 +28,7 @@ EdgeServe AI 的目标用户不应泛泛定义为“所有 LLM 开发者”,
28
 
29
  ## 架构与数据流
30
 
31
- EdgeServe AI 的推荐高层架构如下。其核心原则是:**控制面与数据面分离,在线请求路径尽量短,观测与成本计算异步化,回退路径内建而不是事后补救。**
32
 
33
  ```mermaid
34
  flowchart LR
@@ -356,17 +356,17 @@ Prometheus 官方建议用 histogram + `histogram_quantile()` 做 p95/p99;vLLM
356
 
357
  | 指标名 | 类型 | 说明 |
358
  |---|---|---|
359
- | `edgeserve_request_total{tenant,model,backend,status}` | Counter | 总请求数 |
360
- | `edgeserve_request_latency_seconds` | Histogram | 端到端时延 |
361
- | `edgeserve_ttft_seconds` | Histogram | 首 token 时间 |
362
- | `edgeserve_inter_token_latency_seconds` | Histogram | token 间延迟 |
363
- | `edgeserve_queue_depth{backend}` | Gauge | 调度队列深度 |
364
- | `edgeserve_cache_hit_total{type=exact|prefix|semantic}` | Counter | 各类缓存命中 |
365
- | `edgeserve_provider_cost_usd_total{backend,tenant}` | Counter | 累积成本 |
366
- | `edgeserve_validation_fail_total{reason}` | Counter | 输出校验失败数 |
367
- | `edgeserve_routing_decision_total{policy,backend}` | Counter | 路由落点统计 |
368
- | `edgeserve_fallback_total{from,to,reason}` | Counter | 回退事件 |
369
- | `edgeserve_rate_limited_total{scope}` | Counter | 限流触发数 |
370
 
371
  Grafana 仪表盘建议按四屏组织:
372
  第一屏“服务健康”:QPS、错误率、p50/p95/p99、TTFT。
@@ -413,7 +413,7 @@ RUN pip install --no-cache-dir poetry && poetry config virtualenvs.create false
413
 
414
  COPY . /app
415
  EXPOSE 8080
416
- CMD ["uvicorn", "edgeserve.main:app", "--host", "0.0.0.0", "--port", "8080"]
417
  ```
418
 
419
  ### Kubernetes 示例清单
@@ -422,20 +422,20 @@ CMD ["uvicorn", "edgeserve.main:app", "--host", "0.0.0.0", "--port", "8080"]
422
  apiVersion: apps/v1
423
  kind: Deployment
424
  metadata:
425
- name: edgeserve-gateway
426
  spec:
427
  replicas: 2
428
  selector:
429
  matchLabels:
430
- app: edgeserve-gateway
431
  template:
432
  metadata:
433
  labels:
434
- app: edgeserve-gateway
435
  spec:
436
  containers:
437
  - name: gateway
438
- image: ghcr.io/you/edgeserve:latest
439
  ports:
440
  - containerPort: 8080
441
  env:
@@ -444,7 +444,7 @@ spec:
444
  - name: DATABASE_URL
445
  valueFrom:
446
  secretKeyRef:
447
- name: edgeserve-secrets
448
  key: database-url
449
  readinessProbe:
450
  httpGet:
@@ -465,16 +465,16 @@ spec:
465
  apiVersion: apps/v1
466
  kind: Deployment
467
  metadata:
468
- name: edgeserve-vllm
469
  spec:
470
  replicas: 1
471
  selector:
472
  matchLabels:
473
- app: edgeserve-vllm
474
  template:
475
  metadata:
476
  labels:
477
- app: edgeserve-vllm
478
  spec:
479
  nodeSelector:
480
  accelerator: nvidia
@@ -494,12 +494,12 @@ spec:
494
  apiVersion: autoscaling/v2
495
  kind: HorizontalPodAutoscaler
496
  metadata:
497
- name: edgeserve-gateway-hpa
498
  spec:
499
  scaleTargetRef:
500
  apiVersion: apps/v1
501
  kind: Deployment
502
- name: edgeserve-gateway
503
  minReplicas: 2
504
  maxReplicas: 10
505
  metrics:
@@ -512,7 +512,7 @@ spec:
512
  - type: Pods
513
  pods:
514
  metric:
515
- name: edgeserve_queue_depth
516
  target:
517
  type: AverageValue
518
  averageValue: "20"
 
1
+ # InferRoute 生产级低延迟 LLM 推理路由与可观测平台设计报告
2
 
3
  ## 执行摘要
4
 
5
+ InferRoute 的最佳作品集定位,不是“又一个 AI 聊天壳”,而是一个**面向生产流量的低延迟 LLM Gateway**:它统一接入本地推理引擎与云模型 API,在请求进入后完成鉴权、限流、意图识别、路由决策、缓存命中、流式返回、失败回退、成本归集与端到端可观测。这类项目能同时覆盖 Amazon/Google 偏好的分布式系统、SRE/可观测、API 设计与弹性扩缩,也能覆盖 NVIDIA/Tesla 更看重的推理后端、GPU 调度、量化和吞吐/延迟基准。官方资料表明,vLLM 已提供 OpenAI 兼容服务、前缀缓存、Prometheus 指标与分布式 tensor/pipeline parallel;Ray Serve LLM 则强调多节点推理、自动扩缩、自定义路由与 Grafana 仪表盘;Kubernetes 原生支持 HPA、多指标扩缩与设备插件;OpenTelemetry Collector、Prometheus、Grafana、Jaeger 形成一条标准化、供应商无关的观测链路。citeturn17search9turn18search0turn1search0turn1search1turn0search2turn13search0turn22search2turn23search1turn10search2
6
 
7
  如果只做作品集版本,最推荐的技术路径是:**FastAPI/Starlette API Gateway + 自研 Router/Scheduler + Redis 缓存/队列 + Postgres/pgvector 元数据层 + vLLM 本地 GPU 推理 + OpenAI/Anthropic/Vertex/Azure 适配器 + Prometheus/Grafana/Jaeger**。原因很直接:FastAPI/Starlette 适合快速产出异步 HTTP 和流式响应;Redis 既适合全局限流,也适合消费者组与异步队列;Postgres 可做审计、账单、请求日志与配置,pgvector 可做语义缓存或路由辅助;vLLM 对本地部署最友好,Triton 更适合多框架、动态批处理和 NIM 风格生产环境,ONNX Runtime 更适合边缘与 CPU/轻量 GPU 场景。citeturn16search0turn14search0turn12search0turn12search6turn11search1turn17search9turn18search0turn0search7turn0search1turn19search0turn19search1
8
 
 
10
 
11
  ## 产品目标与系统边界
12
 
13
+ InferRoute 的目标用户不应泛泛定义为“所有 LLM 开发者”,而应明确到三类:
14
 
15
  | 目标用户 | 核心诉求 | 对应价值 |
16
  |---|---|---|
 
28
 
29
  ## 架构与数据流
30
 
31
+ InferRoute 的推荐高层架构如下。其核心原则是:**控制面与数据面分离,在线请求路径尽量短,观测与成本计算异步化,回退路径内建而不是事后补救。**
32
 
33
  ```mermaid
34
  flowchart LR
 
356
 
357
  | 指标名 | 类型 | 说明 |
358
  |---|---|---|
359
+ | `inferroute_request_total{tenant,model,backend,status}` | Counter | 总请求数 |
360
+ | `inferroute_request_latency_seconds` | Histogram | 端到端时延 |
361
+ | `inferroute_ttft_seconds` | Histogram | 首 token 时间 |
362
+ | `inferroute_inter_token_latency_seconds` | Histogram | token 间延迟 |
363
+ | `inferroute_queue_depth{backend}` | Gauge | 调度队列深度 |
364
+ | `inferroute_cache_hit_total{type=exact|prefix|semantic}` | Counter | 各类缓存命中 |
365
+ | `inferroute_provider_cost_usd_total{backend,tenant}` | Counter | 累积成本 |
366
+ | `inferroute_validation_fail_total{reason}` | Counter | 输出校验失败数 |
367
+ | `inferroute_routing_decision_total{policy,backend}` | Counter | 路由落点统计 |
368
+ | `inferroute_fallback_total{from,to,reason}` | Counter | 回退事件 |
369
+ | `inferroute_rate_limited_total{scope}` | Counter | 限流触发数 |
370
 
371
  Grafana 仪表盘建议按四屏组织:
372
  第一屏“服务健康”:QPS、错误率、p50/p95/p99、TTFT。
 
413
 
414
  COPY . /app
415
  EXPOSE 8080
416
+ CMD ["uvicorn", "inferroute.main:app", "--host", "0.0.0.0", "--port", "8080"]
417
  ```
418
 
419
  ### Kubernetes 示例清单
 
422
  apiVersion: apps/v1
423
  kind: Deployment
424
  metadata:
425
+ name: inferroute-gateway
426
  spec:
427
  replicas: 2
428
  selector:
429
  matchLabels:
430
+ app: inferroute-gateway
431
  template:
432
  metadata:
433
  labels:
434
+ app: inferroute-gateway
435
  spec:
436
  containers:
437
  - name: gateway
438
+ image: ghcr.io/you/inferroute:latest
439
  ports:
440
  - containerPort: 8080
441
  env:
 
444
  - name: DATABASE_URL
445
  valueFrom:
446
  secretKeyRef:
447
+ name: inferroute-secrets
448
  key: database-url
449
  readinessProbe:
450
  httpGet:
 
465
  apiVersion: apps/v1
466
  kind: Deployment
467
  metadata:
468
+ name: inferroute-vllm
469
  spec:
470
  replicas: 1
471
  selector:
472
  matchLabels:
473
+ app: inferroute-vllm
474
  template:
475
  metadata:
476
  labels:
477
+ app: inferroute-vllm
478
  spec:
479
  nodeSelector:
480
  accelerator: nvidia
 
494
  apiVersion: autoscaling/v2
495
  kind: HorizontalPodAutoscaler
496
  metadata:
497
+ name: inferroute-gateway-hpa
498
  spec:
499
  scaleTargetRef:
500
  apiVersion: apps/v1
501
  kind: Deployment
502
+ name: inferroute-gateway
503
  minReplicas: 2
504
  maxReplicas: 10
505
  metrics:
 
512
  - type: Pods
513
  pods:
514
  metric:
515
+ name: inferroute_queue_depth
516
  target:
517
  type: AverageValue
518
  averageValue: "20"
edgeserve/__init__.py DELETED
@@ -1 +0,0 @@
1
- # Package initialization
 
 
edgeserve/__pycache__/__init__.cpython-313.pyc DELETED
Binary file (163 Bytes)
 
edgeserve/__pycache__/auth.cpython-313.pyc DELETED
Binary file (3.39 kB)
 
edgeserve/__pycache__/cache.cpython-313.pyc DELETED
Binary file (3.83 kB)
 
edgeserve/__pycache__/config.cpython-313.pyc DELETED
Binary file (1.66 kB)
 
edgeserve/__pycache__/database.cpython-313.pyc DELETED
Binary file (2.17 kB)
 
edgeserve/__pycache__/main.cpython-313.pyc DELETED
Binary file (24.4 kB)
 
edgeserve/__pycache__/models.cpython-313.pyc DELETED
Binary file (3.28 kB)
 
edgeserve/__pycache__/observability.cpython-313.pyc DELETED
Binary file (4.55 kB)
 
edgeserve/__pycache__/router.cpython-313.pyc DELETED
Binary file (9.25 kB)
 
edgeserve/__pycache__/validator.cpython-313.pyc DELETED
Binary file (4.48 kB)
 
edgeserve/adapters/__pycache__/base.cpython-313.pyc DELETED
Binary file (1.24 kB)
 
edgeserve/adapters/__pycache__/openai.cpython-313.pyc DELETED
Binary file (9.53 kB)
 
edgeserve/adapters/__pycache__/vllm.cpython-313.pyc DELETED
Binary file (15.7 kB)
 
edgeserve/adapters/base.py DELETED
@@ -1,19 +0,0 @@
1
- from abc import ABC, abstractmethod
2
- from typing import AsyncGenerator, Any
3
-
4
- class BaseAdapter(ABC):
5
- @abstractmethod
6
- async def generate(self, req: dict[str, Any]) -> dict[str, Any]:
7
- """
8
- Executes a non-streaming chat completion request.
9
- Returns standard OpenAI-like response dictionary.
10
- """
11
- pass
12
-
13
- @abstractmethod
14
- async def generate_stream(self, req: dict[str, Any]) -> AsyncGenerator[dict[str, Any], None]:
15
- """
16
- Executes a streaming chat completion request.
17
- Yields standard OpenAI-like response chunks.
18
- """
19
- pass
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
edgeserve/adapters/openai.py DELETED
@@ -1,206 +0,0 @@
1
- import time
2
- import logging
3
- from typing import AsyncGenerator, Any
4
- from openai import AsyncOpenAI
5
- from edgeserve.adapters.base import BaseAdapter
6
- from edgeserve.config import settings
7
- from edgeserve.observability import tracer, PROVIDER_COST_USD_TOTAL
8
-
9
- logger = logging.getLogger("edgeserve.adapters.openai")
10
-
11
- MODEL_PRICING = {
12
- "gpt-4o-mini": {"input": 0.15 / 1e6, "cached_input": 0.075 / 1e6, "output": 0.60 / 1e6},
13
- "gpt-4o": {"input": 5.0 / 1e6, "cached_input": 2.5 / 1e6, "output": 15.0 / 1e6},
14
- "gpt-3.5-turbo": {"input": 0.50 / 1e6, "cached_input": 0.50 / 1e6, "output": 1.50 / 1e6},
15
- }
16
-
17
- class OpenAIAdapter(BaseAdapter):
18
- def __init__(self):
19
- # Allow testing/mocking with empty or mock api keys
20
- self.client = AsyncOpenAI(api_key=settings.OPENAI_API_KEY)
21
-
22
- def _get_cost(self, model: str, prompt_tokens: int, completion_tokens: int, cached_prompt_tokens: int = 0) -> float:
23
- prices = MODEL_PRICING.get(model, MODEL_PRICING["gpt-4o-mini"])
24
- cost = (
25
- (prompt_tokens - cached_prompt_tokens) * prices["input"]
26
- + cached_prompt_tokens * prices["cached_input"]
27
- + completion_tokens * prices["output"]
28
- )
29
- return cost
30
-
31
- async def generate(self, req: dict[str, Any]) -> dict[str, Any]:
32
- model = req.get("model", "gpt-4o-mini")
33
- if model not in MODEL_PRICING:
34
- # Fallback to mini pricing if custom model name
35
- model = "gpt-4o-mini"
36
-
37
- params = {
38
- "model": model,
39
- "messages": req["messages"],
40
- "temperature": req.get("temperature", 0.7),
41
- "max_tokens": req.get("max_output_tokens", 512),
42
- }
43
- if "response_format" in req:
44
- params["response_format"] = req["response_format"]
45
-
46
- with tracer.start_as_current_span("openai_generate") as span:
47
- span.set_attribute("llm.model", model)
48
- start_time = time.time()
49
-
50
- try:
51
- response = await self.client.chat.completions.create(**params)
52
- latency = time.time() - start_time
53
- span.set_attribute("llm.latency_seconds", latency)
54
-
55
- # Extract usage
56
- prompt_tokens = response.usage.prompt_tokens if response.usage else 0
57
- completion_tokens = response.usage.completion_tokens if response.usage else 0
58
- cached_prompt_tokens = getattr(response.usage, "prompt_tokens_details", None)
59
- cached_tokens = 0
60
- if cached_prompt_tokens and hasattr(cached_prompt_tokens, "cached_tokens"):
61
- cached_tokens = cached_prompt_tokens.cached_tokens
62
-
63
- cost = self._get_cost(model, prompt_tokens, completion_tokens, cached_tokens)
64
-
65
- # Accumulate cost metric
66
- PROVIDER_COST_USD_TOTAL.labels(backend="openai", tenant=req.get("tenant_id", "anonymous")).inc(cost)
67
-
68
- # Map to standard return format
69
- mapped_response = {
70
- "id": response.id,
71
- "object": "chat.completion",
72
- "created": response.created,
73
- "model": response.model,
74
- "choices": [
75
- {
76
- "index": c.index,
77
- "message": {
78
- "role": c.message.role,
79
- "content": c.message.content,
80
- },
81
- "finish_reason": c.finish_reason,
82
- }
83
- for c in response.choices
84
- ],
85
- "usage": {
86
- "prompt_tokens": prompt_tokens,
87
- "completion_tokens": completion_tokens,
88
- "total_tokens": prompt_tokens + completion_tokens,
89
- "cached_prompt_tokens": cached_tokens,
90
- "estimated_cost_usd": cost,
91
- },
92
- "timing": {
93
- "ttft_ms": latency * 1000.0, # non-streaming ttft equals total latency
94
- "latency_ms": latency * 1000.0,
95
- }
96
- }
97
- return mapped_response
98
-
99
- except Exception as e:
100
- span.record_exception(e)
101
- span.set_status(trace.StatusCode.ERROR, str(e))
102
- logger.error(f"OpenAI completion error: {e}")
103
- raise
104
-
105
- async def generate_stream(self, req: dict[str, Any]) -> AsyncGenerator[dict[str, Any], None]:
106
- model = req.get("model", "gpt-4o-mini")
107
- if model not in MODEL_PRICING:
108
- model = "gpt-4o-mini"
109
-
110
- params = {
111
- "model": model,
112
- "messages": req["messages"],
113
- "temperature": req.get("temperature", 0.7),
114
- "max_tokens": req.get("max_output_tokens", 512),
115
- "stream": True,
116
- "stream_options": {"include_usage": True}
117
- }
118
- if "response_format" in req:
119
- params["response_format"] = req["response_format"]
120
-
121
- span = tracer.start_span("openai_generate_stream")
122
- span.set_attribute("llm.model", model)
123
-
124
- start_time = time.time()
125
- ttft_recorded = False
126
- ttft_ms = 0.0
127
-
128
- prompt_tokens = 0
129
- completion_tokens = 0
130
- cached_tokens = 0
131
-
132
- try:
133
- stream = await self.client.chat.completions.create(**params)
134
-
135
- async for chunk in stream:
136
- if not ttft_recorded and len(chunk.choices) > 0 and chunk.choices[0].delta.content:
137
- ttft_ms = (time.time() - start_time) * 1000.0
138
- ttft_recorded = True
139
- span.set_attribute("llm.ttft_seconds", ttft_ms / 1000.0)
140
-
141
- # Check for usage at the end of the stream
142
- if hasattr(chunk, "usage") and chunk.usage:
143
- prompt_tokens = chunk.usage.prompt_tokens
144
- completion_tokens = chunk.usage.completion_tokens
145
- cached_prompt_tokens = getattr(chunk.usage, "prompt_tokens_details", None)
146
- if cached_prompt_tokens and hasattr(cached_prompt_tokens, "cached_tokens"):
147
- cached_tokens = cached_prompt_tokens.cached_tokens
148
-
149
- # Map chunk to standard format
150
- mapped_chunk = {
151
- "id": chunk.id,
152
- "object": "chat.completion.chunk",
153
- "created": chunk.created,
154
- "model": chunk.model,
155
- "choices": [
156
- {
157
- "index": c.index,
158
- "delta": {
159
- "role": getattr(c.delta, "role", None),
160
- "content": getattr(c.delta, "content", None),
161
- },
162
- "finish_reason": c.finish_reason,
163
- }
164
- for c in chunk.choices
165
- ]
166
- }
167
- yield mapped_chunk
168
-
169
- latency_ms = (time.time() - start_time) * 1000.0
170
- span.set_attribute("llm.latency_seconds", latency_ms / 1000.0)
171
-
172
- # If usage details are missing, estimate them based on stream chunks
173
- if prompt_tokens == 0:
174
- # Fallback estimation if stream_options didn't provide usage
175
- prompt_tokens = sum(len(m["content"]) for m in req["messages"]) // 4 + 10
176
- completion_tokens = int(latency_ms / 50.0) # mock output tokens based on avg time
177
-
178
- cost = self._get_cost(model, prompt_tokens, completion_tokens, cached_tokens)
179
- PROVIDER_COST_USD_TOTAL.labels(backend="openai", tenant=req.get("tenant_id", "anonymous")).inc(cost)
180
-
181
- # Yield final statistics block
182
- stats_chunk = {
183
- "id": chunk.id if 'chunk' in locals() else "stream-end",
184
- "object": "chat.completion.chunk",
185
- "choices": [],
186
- "usage": {
187
- "prompt_tokens": prompt_tokens,
188
- "completion_tokens": completion_tokens,
189
- "total_tokens": prompt_tokens + completion_tokens,
190
- "cached_prompt_tokens": cached_tokens,
191
- "estimated_cost_usd": cost,
192
- },
193
- "timing": {
194
- "ttft_ms": ttft_ms if ttft_recorded else latency_ms,
195
- "latency_ms": latency_ms,
196
- }
197
- }
198
- yield stats_chunk
199
- span.end()
200
-
201
- except Exception as e:
202
- span.record_exception(e)
203
- span.set_status(trace.StatusCode.ERROR, str(e))
204
- span.end()
205
- logger.error(f"OpenAI streaming error: {e}")
206
- raise
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
edgeserve/adapters/vllm.py DELETED
@@ -1,358 +0,0 @@
1
- import asyncio
2
- import time
3
- import logging
4
- from typing import AsyncGenerator, Any
5
- import httpx
6
- from edgeserve.adapters.base import BaseAdapter
7
- from edgeserve.config import settings
8
- from edgeserve.observability import tracer, PROVIDER_COST_USD_TOTAL
9
-
10
- logger = logging.getLogger("edgeserve.adapters.vllm")
11
-
12
- # Local GPU/CPU amortized cost estimate per token
13
- LOCAL_INPUT_COST = 0.000005 / 1000 # $0.005 per 1K tokens
14
- LOCAL_OUTPUT_COST = 0.000015 / 1000 # $0.015 per 1K tokens
15
-
16
- class VLLMAdapter(BaseAdapter):
17
- def __init__(self):
18
- self.api_url = settings.VLLM_API_URL
19
- self.api_key = settings.VLLM_API_KEY
20
- self.mock_mode = settings.MOCK_VLLM
21
- self.client = httpx.AsyncClient(
22
- headers={"Authorization": f"Bearer {self.api_key}"} if self.api_key else {}
23
- )
24
-
25
- def _get_cost(self, prompt_tokens: int, completion_tokens: int) -> float:
26
- # Local model cost is derived from hardware amortization estimates
27
- return (prompt_tokens * LOCAL_INPUT_COST) + (completion_tokens * LOCAL_OUTPUT_COST)
28
-
29
- async def generate(self, req: dict[str, Any]) -> dict[str, Any]:
30
- if self.mock_mode:
31
- return await self._mock_generate(req)
32
-
33
- model = req.get("model", "meta-llama/Meta-Llama-3-8B-Instruct")
34
- params = {
35
- "model": model,
36
- "messages": req["messages"],
37
- "temperature": req.get("temperature", 0.7),
38
- "max_tokens": req.get("max_output_tokens", 512),
39
- "stream": False
40
- }
41
- if "response_format" in req:
42
- params["response_format"] = req["response_format"]
43
-
44
- with tracer.start_as_current_span("vllm_generate") as span:
45
- span.set_attribute("llm.model", model)
46
- start_time = time.time()
47
- try:
48
- response = await self.client.post(
49
- f"{self.api_url}/chat/completions",
50
- json=params,
51
- timeout=30.0
52
- )
53
- response.raise_for_status()
54
- data = response.json()
55
- latency = time.time() - start_time
56
- span.set_attribute("llm.latency_seconds", latency)
57
-
58
- # Extract usage and cost
59
- usage = data.get("usage", {})
60
- prompt_tokens = usage.get("prompt_tokens", 0)
61
- completion_tokens = usage.get("completion_tokens", 0)
62
- cost = self._get_cost(prompt_tokens, completion_tokens)
63
-
64
- PROVIDER_COST_USD_TOTAL.labels(backend="vllm", tenant=req.get("tenant_id", "anonymous")).inc(cost)
65
-
66
- # Map to consistent output
67
- choices = data.get("choices", [])
68
- mapped_choices = []
69
- for idx, c in enumerate(choices):
70
- msg = c.get("message", {})
71
- mapped_choices.append({
72
- "index": c.get("index", idx),
73
- "message": {
74
- "role": msg.get("role", "assistant"),
75
- "content": msg.get("content", ""),
76
- },
77
- "finish_reason": c.get("finish_reason", "stop")
78
- })
79
-
80
- return {
81
- "id": data.get("id", "vllm-completion"),
82
- "object": "chat.completion",
83
- "created": data.get("created", int(time.time())),
84
- "model": data.get("model", model),
85
- "choices": mapped_choices,
86
- "usage": {
87
- "prompt_tokens": prompt_tokens,
88
- "completion_tokens": completion_tokens,
89
- "total_tokens": prompt_tokens + completion_tokens,
90
- "cached_prompt_tokens": usage.get("prompt_tokens_details", {}).get("cached_tokens", 0),
91
- "estimated_cost_usd": cost,
92
- },
93
- "timing": {
94
- "ttft_ms": latency * 1000.0,
95
- "latency_ms": latency * 1000.0,
96
- }
97
- }
98
- except Exception as e:
99
- span.record_exception(e)
100
- span.set_status(trace.StatusCode.ERROR, str(e))
101
- logger.error(f"vLLM API HTTP request failed: {e}")
102
- raise
103
-
104
- async def generate_stream(self, req: dict[str, Any]) -> AsyncGenerator[dict[str, Any], None]:
105
- if self.mock_mode:
106
- async for chunk in self._mock_generate_stream(req):
107
- yield chunk
108
- return
109
-
110
- model = req.get("model", "meta-llama/Meta-Llama-3-8B-Instruct")
111
- params = {
112
- "model": model,
113
- "messages": req["messages"],
114
- "temperature": req.get("temperature", 0.7),
115
- "max_tokens": req.get("max_output_tokens", 512),
116
- "stream": True,
117
- "stream_options": {"include_usage": True}
118
- }
119
- if "response_format" in req:
120
- params["response_format"] = req["response_format"]
121
-
122
- span = tracer.start_span("vllm_generate_stream")
123
- span.set_attribute("llm.model", model)
124
-
125
- start_time = time.time()
126
- ttft_recorded = False
127
- ttft_ms = 0.0
128
-
129
- prompt_tokens = 0
130
- completion_tokens = 0
131
-
132
- try:
133
- # We use a custom event stream reader
134
- async with self.client.stream("POST", f"{self.api_url}/chat/completions", json=params, timeout=30.0) as response:
135
- response.raise_for_status()
136
-
137
- async for line in response.aiter_lines():
138
- line = line.strip()
139
- if not line:
140
- continue
141
- if line == "data: [DONE]":
142
- break
143
- if line.startswith("data: "):
144
- import json
145
- try:
146
- chunk_data = json.loads(line[6:])
147
- choices = chunk_data.get("choices", [])
148
-
149
- if not ttft_recorded and len(choices) > 0 and choices[0].get("delta", {}).get("content"):
150
- ttft_ms = (time.time() - start_time) * 1000.0
151
- ttft_recorded = True
152
- span.set_attribute("llm.ttft_seconds", ttft_ms / 1000.0)
153
-
154
- usage = chunk_data.get("usage")
155
- if usage:
156
- prompt_tokens = usage.get("prompt_tokens", 0)
157
- completion_tokens = usage.get("completion_tokens", 0)
158
-
159
- # Standardize chunk
160
- mapped_choices = []
161
- for idx, c in enumerate(choices):
162
- delta = c.get("delta", {})
163
- mapped_choices.append({
164
- "index": c.get("index", idx),
165
- "delta": {
166
- "role": delta.get("role"),
167
- "content": delta.get("content"),
168
- },
169
- "finish_reason": c.get("finish_reason")
170
- })
171
-
172
- mapped_chunk = {
173
- "id": chunk_data.get("id"),
174
- "object": "chat.completion.chunk",
175
- "created": chunk_data.get("created"),
176
- "model": chunk_data.get("model", model),
177
- "choices": mapped_choices
178
- }
179
- yield mapped_chunk
180
- except Exception as e:
181
- logger.error(f"Error parsing vLLM stream line: {line}. Error: {e}")
182
-
183
- latency_ms = (time.time() - start_time) * 1000.0
184
- span.set_attribute("llm.latency_seconds", latency_ms / 1000.0)
185
-
186
- if prompt_tokens == 0:
187
- prompt_tokens = sum(len(m["content"]) for m in req["messages"]) // 4 + 10
188
- completion_tokens = int(latency_ms / 30.0)
189
-
190
- cost = self._get_cost(prompt_tokens, completion_tokens)
191
- PROVIDER_COST_USD_TOTAL.labels(backend="vllm", tenant=req.get("tenant_id", "anonymous")).inc(cost)
192
-
193
- stats_chunk = {
194
- "id": "vllm-stream-end",
195
- "object": "chat.completion.chunk",
196
- "choices": [],
197
- "usage": {
198
- "prompt_tokens": prompt_tokens,
199
- "completion_tokens": completion_tokens,
200
- "total_tokens": prompt_tokens + completion_tokens,
201
- "cached_prompt_tokens": 0,
202
- "estimated_cost_usd": cost,
203
- },
204
- "timing": {
205
- "ttft_ms": ttft_ms if ttft_recorded else latency_ms,
206
- "latency_ms": latency_ms,
207
- }
208
- }
209
- yield stats_chunk
210
- span.end()
211
-
212
- except Exception as e:
213
- span.record_exception(e)
214
- span.set_status(trace.StatusCode.ERROR, str(e))
215
- span.end()
216
- logger.error(f"vLLM streaming error: {e}")
217
- raise
218
-
219
- # --- MOCK MODE IMPLEMENTATIONS ---
220
-
221
- async def _mock_generate(self, req: dict[str, Any]) -> dict[str, Any]:
222
- """Simulates non-streaming generation with mock latency."""
223
- with tracer.start_as_current_span("vllm_mock_generate") as span:
224
- model = req.get("model", "meta-llama/Meta-Llama-3-8B-Instruct")
225
- span.set_attribute("llm.model", model)
226
-
227
- # Simulate processing delay: ~150ms TTFT + ~15ms per token for 100 tokens -> ~1.65 seconds
228
- prompt_len = sum(len(m["content"]) for m in req["messages"])
229
- prompt_tokens = prompt_len // 4 + 5
230
- completion_tokens = 80
231
-
232
- # Simulated delay
233
- await asyncio.sleep(0.3)
234
-
235
- cost = self._get_cost(prompt_tokens, completion_tokens)
236
- PROVIDER_COST_USD_TOTAL.labels(backend="vllm", tenant=req.get("tenant_id", "anonymous")).inc(cost)
237
-
238
- content = "This is a mock response from local vLLM. It matches your structural design patterns and is fully functional."
239
- if "response_format" in req and req["response_format"].get("type") == "json_schema":
240
- content = '{"invoice_id": "MOCK-12345", "amount": 99.99}'
241
-
242
- return {
243
- "id": "mock-vllm-completion-123",
244
- "object": "chat.completion",
245
- "created": int(time.time()),
246
- "model": model,
247
- "choices": [
248
- {
249
- "index": 0,
250
- "message": {
251
- "role": "assistant",
252
- "content": content,
253
- },
254
- "finish_reason": "stop"
255
- }
256
- ],
257
- "usage": {
258
- "prompt_tokens": prompt_tokens,
259
- "completion_tokens": completion_tokens,
260
- "total_tokens": prompt_tokens + completion_tokens,
261
- "cached_prompt_tokens": 0,
262
- "estimated_cost_usd": cost,
263
- },
264
- "timing": {
265
- "ttft_ms": 150.0,
266
- "latency_ms": 300.0,
267
- }
268
- }
269
-
270
- async def _mock_generate_stream(self, req: dict[str, Any]) -> AsyncGenerator[dict[str, Any], None]:
271
- """Simulates streaming token generation with mock interval delays."""
272
- span = tracer.start_span("vllm_mock_generate_stream")
273
- model = req.get("model", "meta-llama/Meta-Llama-3-8B-Instruct")
274
- span.set_attribute("llm.model", model)
275
-
276
- prompt_len = sum(len(m["content"]) for m in req["messages"])
277
- prompt_tokens = prompt_len // 4 + 5
278
-
279
- # Stream chunks simulation
280
- content = "This is a streaming mock response from local vLLM. It confirms execution paths and fallback routes."
281
- if "response_format" in req and req["response_format"].get("type") == "json_schema":
282
- content = '{"invoice_id": "MOCK-STREAM-99", "amount": 42.50}'
283
-
284
- words = content.split(" ")
285
-
286
- # 1. Simulate TTFT (initial wait)
287
- start_time = time.time()
288
- await asyncio.sleep(0.12) # 120ms wait
289
- ttft_ms = (time.time() - start_time) * 1000.0
290
- span.set_attribute("llm.ttft_seconds", ttft_ms / 1000.0)
291
-
292
- # Send first delta block
293
- yield {
294
- "id": "mock-vllm-stream-chunk",
295
- "object": "chat.completion.chunk",
296
- "created": int(time.time()),
297
- "model": model,
298
- "choices": [{
299
- "index": 0,
300
- "delta": {"role": "assistant", "content": ""},
301
- "finish_reason": None
302
- }]
303
- }
304
-
305
- # 2. Stream word by word
306
- for i, word in enumerate(words):
307
- await asyncio.sleep(0.02) # 20ms between tokens
308
- chunk_content = word if i == 0 else " " + word
309
- yield {
310
- "id": "mock-vllm-stream-chunk",
311
- "object": "chat.completion.chunk",
312
- "created": int(time.time()),
313
- "model": model,
314
- "choices": [{
315
- "index": 0,
316
- "delta": {"role": None, "content": chunk_content},
317
- "finish_reason": None
318
- }]
319
- }
320
-
321
- # 3. Stream finalize Choice
322
- yield {
323
- "id": "mock-vllm-stream-chunk",
324
- "object": "chat.completion.chunk",
325
- "created": int(time.time()),
326
- "model": model,
327
- "choices": [{
328
- "index": 0,
329
- "delta": {"role": None, "content": None},
330
- "finish_reason": "stop"
331
- }]
332
- }
333
-
334
- latency_ms = (time.time() - start_time) * 1000.0
335
- span.set_attribute("llm.latency_seconds", latency_ms / 1000.0)
336
- completion_tokens = len(words) * 2 # estimate 2 tokens per word
337
-
338
- cost = self._get_cost(prompt_tokens, completion_tokens)
339
- PROVIDER_COST_USD_TOTAL.labels(backend="vllm", tenant=req.get("tenant_id", "anonymous")).inc(cost)
340
-
341
- # Yield statistics block
342
- yield {
343
- "id": "mock-vllm-stream-chunk",
344
- "object": "chat.completion.chunk",
345
- "choices": [],
346
- "usage": {
347
- "prompt_tokens": prompt_tokens,
348
- "completion_tokens": completion_tokens,
349
- "total_tokens": prompt_tokens + completion_tokens,
350
- "cached_prompt_tokens": 0,
351
- "estimated_cost_usd": cost,
352
- },
353
- "timing": {
354
- "ttft_ms": ttft_ms,
355
- "latency_ms": latency_ms,
356
- }
357
- }
358
- span.end()
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
edgeserve/auth.py DELETED
@@ -1,77 +0,0 @@
1
- import time
2
- import logging
3
- from typing import Optional
4
- from fastapi import HTTPException, Security, status
5
- from fastapi.security import HTTPBearer, HTTPAuthorizationCredentials
6
- import redis.asyncio as aioredis
7
- from edgeserve.config import settings
8
- from edgeserve.observability import RATE_LIMITED_TOTAL
9
-
10
- logger = logging.getLogger("edgeserve.auth")
11
- security = HTTPBearer()
12
-
13
- # Static API key mapping for MVP demo
14
- API_KEYS = {
15
- "sk-edgeserve-demo": "acme_corp",
16
- "sk-edgeserve-dev": "internal_dev",
17
- settings.ADMIN_API_KEY: "admin"
18
- }
19
-
20
- # Redis Client Instance placeholder (initialized in main.py)
21
- redis_client: Optional[aioredis.Redis] = None
22
-
23
- def get_redis_client() -> Optional[aioredis.Redis]:
24
- global redis_client
25
- return redis_client
26
-
27
- async def verify_api_key(credentials: HTTPAuthorizationCredentials = Security(security)) -> str:
28
- """
29
- Verifies the provided API key and returns the associated tenant ID.
30
- Supports standard Bearer token header.
31
- """
32
- token = credentials.credentials
33
- if token in API_KEYS:
34
- return API_KEYS[token]
35
-
36
- raise HTTPException(
37
- status_code=status.HTTP_401_UNAUTHORIZED,
38
- detail="Invalid API Key"
39
- )
40
-
41
- async def check_rate_limit(tenant_id: str) -> None:
42
- """
43
- Checks request rate limits for a given tenant using Redis.
44
- Limits requests per minute (RPM).
45
- Fails open (logs a warning and continues) if Redis is unavailable.
46
- """
47
- client = get_redis_client()
48
- if client is None:
49
- logger.warning("Redis is not configured. Skipping rate limit checks.")
50
- return
51
-
52
- try:
53
- # Determine tenant limit
54
- limit = settings.DEFAULT_RATE_LIMIT_RPM
55
- if tenant_id == "admin":
56
- limit = 999999 # effectively unlimited
57
-
58
- current_minute = int(time.time() / 60)
59
- key = f"rate_limit:{tenant_id}:{current_minute}"
60
-
61
- # Increment request count for current minute window
62
- requests = await client.incr(key)
63
- if requests == 1:
64
- await client.expire(key, 60)
65
-
66
- if requests > limit:
67
- RATE_LIMITED_TOTAL.labels(scope="tenant").inc()
68
- raise HTTPException(
69
- status_code=status.HTTP_429_TOO_MANY_REQUESTS,
70
- detail=f"Rate limit exceeded. Maximum allowed is {limit} RPM."
71
- )
72
-
73
- except HTTPException:
74
- raise
75
- except Exception as e:
76
- logger.error(f"Redis rate limiter exception: {e}. Bypassing rate limiting.")
77
- return
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
edgeserve/cache.py DELETED
@@ -1,60 +0,0 @@
1
- import hashlib
2
- import json
3
- import logging
4
- from typing import Optional, Any
5
- from edgeserve.auth import get_redis_client
6
- from edgeserve.observability import CACHE_HIT_TOTAL
7
-
8
- logger = logging.getLogger("edgeserve.cache")
9
-
10
- class CacheLayer:
11
- @staticmethod
12
- def _exact_key(req: dict[str, Any]) -> str:
13
- """
14
- Creates a deterministic hash of the request dictionary to serve as cache key.
15
- Excludes optional keys like metadata, routing, and stream which do not affect content generation.
16
- """
17
- # Create a copy to avoid mutating the original request
18
- clean_req = req.copy()
19
- clean_req.pop("routing", None)
20
- clean_req.pop("metadata", None)
21
- clean_req.pop("stream", None) # Caching is content-based; we store & return non-stream response representation
22
-
23
- # Canonicalize JSON
24
- canonical = json.dumps(clean_req, sort_keys=True, ensure_ascii=False)
25
- return "edgeserve:cache:exact:" + hashlib.sha256(canonical.encode("utf-8")).hexdigest()
26
-
27
- async def lookup_exact(self, req: dict[str, Any]) -> Optional[dict[str, Any]]:
28
- """
29
- Looks up an exact request in Redis cache. Returns the parsed response dict if hit, else None.
30
- """
31
- client = get_redis_client()
32
- if client is None:
33
- return None
34
-
35
- try:
36
- key = self._exact_key(req)
37
- raw = await client.get(key)
38
- if raw:
39
- logger.info(f"Exact cache HIT for request hash: {key}")
40
- CACHE_HIT_TOTAL.labels(type="exact").inc()
41
- return json.loads(raw)
42
- except Exception as e:
43
- logger.error(f"Redis cache lookup error: {e}")
44
-
45
- return None
46
-
47
- async def store_exact(self, req: dict[str, Any], resp: dict[str, Any], ttl_sec: int = 300) -> None:
48
- """
49
- Stores a response dictionary in Redis cache with a TTL (Time-To-Live).
50
- """
51
- client = get_redis_client()
52
- if client is None:
53
- return
54
-
55
- try:
56
- key = self._exact_key(req)
57
- await client.set(key, json.dumps(resp, ensure_ascii=False), ex=ttl_sec)
58
- logger.info(f"Stored response in cache with key: {key}, TTL: {ttl_sec}s")
59
- except Exception as e:
60
- logger.error(f"Redis cache store error: {e}")
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
edgeserve/config.py DELETED
@@ -1,41 +0,0 @@
1
- import os
2
- from pydantic_settings import BaseSettings, SettingsConfigDict
3
- from pydantic import Field
4
-
5
- class Settings(BaseSettings):
6
- ENV: str = Field(default="development", validation_alias="ENV")
7
-
8
- # Databases
9
- DATABASE_URL: str = Field(
10
- default="postgresql+asyncpg://postgres:postgres@localhost:5432/edgeserve",
11
- validation_alias="DATABASE_URL"
12
- )
13
- REDIS_URL: str = Field(
14
- default="redis://localhost:6379/0",
15
- validation_alias="REDIS_URL"
16
- )
17
-
18
- # API Keys & Third-party integrations
19
- OPENAI_API_KEY: str = Field(default="mock-key", validation_alias="OPENAI_API_KEY")
20
- VLLM_API_URL: str = Field(default="http://localhost:8000/v1", validation_alias="VLLM_API_URL")
21
- VLLM_API_KEY: str = Field(default="mock-vllm-key", validation_alias="VLLM_API_KEY")
22
- MOCK_VLLM: bool = Field(default=True, validation_alias="MOCK_VLLM")
23
-
24
- # Gatekeeper settings
25
- ADMIN_API_KEY: str = Field(default="admin-secret", validation_alias="ADMIN_API_KEY")
26
- DEFAULT_RATE_LIMIT_RPM: int = Field(default=60, validation_alias="DEFAULT_RATE_LIMIT_RPM")
27
-
28
- # Observability
29
- OTEL_EXPORTER_OTLP_ENDPOINT: str = Field(
30
- default="http://localhost:4317",
31
- validation_alias="OTEL_EXPORTER_OTLP_ENDPOINT"
32
- )
33
- SERVICE_NAME: str = "edgeserve-gateway"
34
-
35
- model_config = SettingsConfigDict(
36
- env_file=".env",
37
- env_file_encoding="utf-8",
38
- extra="ignore"
39
- )
40
-
41
- settings = Settings()
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
edgeserve/database.py DELETED
@@ -1,37 +0,0 @@
1
- from typing import AsyncGenerator
2
- from sqlalchemy.ext.asyncio import create_async_engine, async_sessionmaker, AsyncSession
3
- from edgeserve.config import settings
4
- from edgeserve.models import Base
5
-
6
- # Create async engine
7
- engine = create_async_engine(
8
- settings.DATABASE_URL,
9
- echo=False,
10
- pool_size=10,
11
- max_overflow=20
12
- )
13
-
14
- # Async session factory
15
- async_session = async_sessionmaker(
16
- bind=engine,
17
- class_=AsyncSession,
18
- expire_on_commit=False
19
- )
20
-
21
- async def init_db() -> None:
22
- """Initialize database tables."""
23
- async with engine.begin() as conn:
24
- # For development ease, we auto-create the schema
25
- await conn.run_sync(Base.metadata.create_all)
26
-
27
- async def get_db() -> AsyncGenerator[AsyncSession, None]:
28
- """Dependency for getting database sessions."""
29
- async with async_session() as session:
30
- try:
31
- yield session
32
- await session.commit()
33
- except Exception:
34
- await session.rollback()
35
- raise
36
- finally:
37
- await session.close()
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
edgeserve/main.py DELETED
@@ -1,598 +0,0 @@
1
- import json
2
- import time
3
- import uuid
4
- import logging
5
- from contextlib import asynccontextmanager
6
- from typing import Any, AsyncGenerator, Optional
7
-
8
- from fastapi import FastAPI, Depends, HTTPException, Security, status, Request, BackgroundTasks
9
- from fastapi.responses import StreamingResponse
10
- import redis.asyncio as aioredis
11
- from sqlalchemy.ext.asyncio import AsyncSession
12
-
13
- from edgeserve.config import settings
14
- from edgeserve.database import init_db, get_db, async_session
15
- from edgeserve.models import RequestLog
16
- from edgeserve.auth import verify_api_key, check_rate_limit
17
- from edgeserve.cache import CacheLayer
18
- from edgeserve.router import Router
19
- from edgeserve.validator import OutputValidator
20
- from edgeserve.adapters.openai import OpenAIAdapter
21
- from edgeserve.adapters.vllm import VLLMAdapter
22
- from edgeserve.observability import (
23
- setup_observability,
24
- get_metrics_response,
25
- REQUESTS_TOTAL,
26
- REQUEST_LATENCY,
27
- TTFT_LATENCY,
28
- INTER_TOKEN_LATENCY,
29
- FALLBACK_TOTAL,
30
- QUEUE_DEPTH
31
- )
32
-
33
- # Setup logging
34
- logging.basicConfig(level=logging.INFO)
35
- logger = logging.getLogger("edgeserve.main")
36
-
37
- # Instantiate adapters
38
- openai_adapter = OpenAIAdapter()
39
- vllm_adapter = VLLMAdapter()
40
-
41
- ADAPTERS = {
42
- "openai": openai_adapter,
43
- "vllm": vllm_adapter
44
- }
45
-
46
- router_engine = Router()
47
- validator = OutputValidator()
48
- cache_layer = CacheLayer()
49
-
50
- @asynccontextmanager
51
- async def lifespan(app: FastAPI):
52
- # Startup: Initialize DB & Redis
53
- logger.info("Initializing databases and external services...")
54
- await init_db()
55
-
56
- # Initialize global Redis client in auth module
57
- import edgeserve.auth as auth
58
- auth.redis_client = aioredis.from_url(settings.REDIS_URL, decode_responses=True)
59
- logger.info("Lifespan setup completed successfully.")
60
- yield
61
- # Shutdown: Close connections
62
- if auth.redis_client:
63
- await auth.redis_client.close()
64
- logger.info("Redis connection closed.")
65
-
66
- app = FastAPI(
67
- title="EdgeServe AI Gateway",
68
- description="Production-grade low latency LLM inference router and observability gateway",
69
- version="0.1.0",
70
- lifespan=lifespan
71
- )
72
-
73
- # Setup OTel instrumentation
74
- setup_observability(app)
75
-
76
- # Helper function to write logs to PostgreSQL in the background
77
- async def db_log_request(
78
- tenant_id: str,
79
- model: str,
80
- logical_model: str,
81
- prompt_tokens: int,
82
- completion_tokens: int,
83
- cost_usd: float,
84
- cache_hit: bool,
85
- cache_type: str | None,
86
- primary_backend: str,
87
- selected_backend: str,
88
- fallback_count: int,
89
- status_str: str,
90
- error_message: str | None,
91
- queue_ms: float,
92
- ttft_ms: float,
93
- latency_ms: float
94
- ):
95
- async with async_session() as session:
96
- try:
97
- log_entry = RequestLog(
98
- tenant_id=tenant_id,
99
- model=model,
100
- logical_model=logical_model,
101
- prompt_tokens=prompt_tokens,
102
- completion_tokens=completion_tokens,
103
- total_tokens=prompt_tokens + completion_tokens,
104
- cost_usd=cost_usd,
105
- cache_hit=cache_hit,
106
- cache_type=cache_type,
107
- primary_backend=primary_backend,
108
- selected_backend=selected_backend,
109
- fallback_count=fallback_count,
110
- status=status_str,
111
- error_message=error_message,
112
- timing_queue_ms=queue_ms,
113
- timing_ttft_ms=ttft_ms,
114
- timing_latency_ms=latency_ms
115
- )
116
- session.add(log_entry)
117
- await session.commit()
118
- except Exception as e:
119
- logger.error(f"Failed to write request log to PostgreSQL: {e}")
120
-
121
- @app.get("/healthz", status_code=status.HTTP_200_OK)
122
- async def healthz():
123
- return {"status": "ok", "timestamp": time.time()}
124
-
125
- @app.get("/readyz")
126
- async def readyz():
127
- import edgeserve.auth as auth
128
- status_info = {"postgres": "unhealthy", "redis": "unhealthy"}
129
-
130
- # Check Postgres
131
- try:
132
- async with async_session() as session:
133
- await session.execute("SELECT 1")
134
- status_info["postgres"] = "healthy"
135
- except Exception as e:
136
- logger.error(f"Readyz Postgres healthcheck failed: {e}")
137
-
138
- # Check Redis
139
- try:
140
- if auth.redis_client:
141
- await auth.redis_client.ping()
142
- status_info["redis"] = "healthy"
143
- except Exception as e:
144
- logger.error(f"Readyz Redis healthcheck failed: {e}")
145
-
146
- if "unhealthy" in status_info.values():
147
- raise HTTPException(
148
- status_code=status.HTTP_503_SERVICE_UNAVAILABLE,
149
- detail={"status": "degraded", "components": status_info}
150
- )
151
-
152
- return {"status": "ready", "components": status_info}
153
-
154
- @app.get("/metrics")
155
- async def metrics():
156
- content, media_type = get_metrics_response()
157
- from fastapi.responses import Response
158
- return Response(content=content, media_type=media_type)
159
-
160
- @app.get("/v1/models")
161
- async def list_models(tenant_id: str = Depends(verify_api_key)):
162
- return {
163
- "object": "list",
164
- "data": [
165
- {"id": "edge/auto", "object": "model", "owned_by": "edgeserve"},
166
- {"id": "gpt-4o-mini", "object": "model", "owned_by": "openai"},
167
- {"id": "meta-llama/Meta-Llama-3-8B-Instruct", "object": "model", "owned_by": "meta"}
168
- ]
169
- }
170
-
171
- @app.post("/v1/chat/completions")
172
- async def chat_completions(
173
- request: Request,
174
- background_tasks: BackgroundTasks,
175
- tenant_id: str = Depends(verify_api_key)
176
- ):
177
- # Retrieve body
178
- try:
179
- body = await request.json()
180
- except Exception:
181
- raise HTTPException(status_code=400, detail="Invalid JSON body")
182
-
183
- # Rate limit check
184
- await check_rate_limit(tenant_id)
185
-
186
- # Inject tenant_id into request dict for adapters/logging usage
187
- body["tenant_id"] = tenant_id
188
-
189
- model_req = body.get("model", "edge/auto")
190
- stream_req = body.get("stream", False)
191
-
192
- # 1. Exact Cache Lookup
193
- cached_resp = await cache_layer.lookup_exact(body)
194
- if cached_resp:
195
- REQUESTS_TOTAL.labels(tenant=tenant_id, model=model_req, backend="cache", status="completed").inc()
196
-
197
- # Log to PostgreSQL asynchronously
198
- background_tasks.add_task(
199
- db_log_request,
200
- tenant_id=tenant_id,
201
- model=cached_resp.get("model", model_req),
202
- logical_model=model_req,
203
- prompt_tokens=cached_resp.get("usage", {}).get("prompt_tokens", 0),
204
- completion_tokens=cached_resp.get("usage", {}).get("completion_tokens", 0),
205
- cost_usd=0.0, # cache hit has no token costs
206
- cache_hit=True,
207
- cache_type="exact",
208
- primary_backend="cache",
209
- selected_backend="cache",
210
- fallback_count=0,
211
- status_str="completed",
212
- error_message=None,
213
- queue_ms=0.0,
214
- ttft_ms=5.0, # mock minimum lookup latency
215
- latency_ms=5.0
216
- )
217
-
218
- if stream_req:
219
- # Yield cached response structured as chunks
220
- async def cache_stream():
221
- chunk_id = f"chatcmpl-{uuid.uuid4()}"
222
- choices = cached_resp.get("choices", [])
223
- content = choices[0].get("message", {}).get("content", "") if choices else ""
224
-
225
- # Yield initial role delta
226
- yield f"data: {json.dumps({'id': chunk_id, 'object': 'chat.completion.chunk', 'choices': [{'index': 0, 'delta': {'role': 'assistant', 'content': ''}, 'finish_reason': None}]})}\n\n"
227
-
228
- # Yield full content
229
- yield f"data: {json.dumps({'id': chunk_id, 'object': 'chat.completion.chunk', 'choices': [{'index': 0, 'delta': {'role': None, 'content': content}, 'finish_reason': 'stop'}]})}\n\n"
230
-
231
- # Yield statistics
232
- yield f"data: {json.dumps({'id': chunk_id, 'object': 'chat.completion.chunk', 'choices': [], 'usage': cached_resp.get('usage', {})})}\n\n"
233
- yield "data: [DONE]\n\n"
234
-
235
- return StreamingResponse(
236
- cache_stream(),
237
- media_type="text/event-stream",
238
- headers={"Cache-Control": "no-cache", "Connection": "keep-alive"}
239
- )
240
- else:
241
- return cached_resp
242
-
243
- # 2. Routing Decision
244
- primary_backend, fallback_backend, route_reason = await router_engine.choose_backend(body)
245
-
246
- # 3. Execution (Non-Streaming vs Streaming)
247
- if stream_req:
248
- return await handle_streaming_flow(
249
- body, tenant_id, primary_backend, fallback_backend, background_tasks
250
- )
251
- else:
252
- return await handle_blocking_flow(
253
- body, tenant_id, primary_backend, fallback_backend, background_tasks
254
- )
255
-
256
- # --- FLOW ORCHESTRATION IMPLEMENTATIONS ---
257
-
258
- async def handle_blocking_flow(
259
- req: dict[str, Any],
260
- tenant_id: str,
261
- primary: str,
262
- fallback: Optional[str],
263
- background_tasks: BackgroundTasks
264
- ) -> dict[str, Any]:
265
- model_req = req.get("model", "edge/auto")
266
-
267
- # Track metrics
268
- start_time = time.time()
269
- fallback_count = 0
270
- selected_backend = primary
271
- error_msg = None
272
- status_str = "completed"
273
-
274
- # Update queue depths
275
- QUEUE_DEPTH.labels(backend=primary).inc()
276
-
277
- try:
278
- # Step 1: Call primary backend
279
- logger.info(f"Invoking primary backend: {primary}")
280
- resp = await ADAPTERS[primary].generate(req)
281
-
282
- # Step 2: Validate Output
283
- val_res = validator.validate_response(req, resp)
284
- if not val_res.ok:
285
- raise ValueError(f"validation_failed: {val_res.reason}")
286
-
287
- except Exception as primary_exc:
288
- # Primary failed, attempt fallback if available
289
- logger.warning(f"Primary backend {primary} failed. Error: {primary_exc}")
290
- if fallback:
291
- logger.info(f"Attempting fallback backend: {fallback}")
292
- fallback_count += 1
293
- selected_backend = fallback
294
- FALLBACK_TOTAL.labels(from_backend=primary, to_backend=fallback, reason=str(primary_exc)).inc()
295
-
296
- QUEUE_DEPTH.labels(backend=primary).dec()
297
- QUEUE_DEPTH.labels(backend=fallback).inc()
298
-
299
- try:
300
- resp = await ADAPTERS[fallback].generate(req)
301
- val_res = validator.validate_response(req, resp)
302
- if not val_res.ok:
303
- status_str = "validation_failed"
304
- error_msg = f"Fallback validation failed: {val_res.reason}"
305
- raise HTTPException(status_code=422, detail=error_msg)
306
- except Exception as fallback_exc:
307
- status_str = "failed"
308
- error_msg = f"Fallback failed: {fallback_exc}"
309
- logger.error(f"Fallback backend {fallback} also failed: {fallback_exc}")
310
-
311
- # Log execution record
312
- latency_ms = (time.time() - start_time) * 1000.0
313
- background_tasks.add_task(
314
- db_log_request, tenant_id=tenant_id, model=model_req, logical_model=model_req,
315
- prompt_tokens=0, completion_tokens=0, cost_usd=0.0, cache_hit=False, cache_type=None,
316
- primary_backend=primary, selected_backend=selected_backend, fallback_count=fallback_count,
317
- status_str=status_str, error_message=error_msg, queue_ms=0.0, ttft_ms=0.0, latency_ms=latency_ms
318
- )
319
-
320
- # Update metrics
321
- REQUESTS_TOTAL.labels(tenant=tenant_id, model=model_req, backend=selected_backend, status=status_str).inc()
322
- await router_engine.record_metrics(selected_backend, 0.0, latency_ms, success=False)
323
-
324
- QUEUE_DEPTH.labels(backend=selected_backend).dec()
325
- raise HTTPException(status_code=502, detail=error_msg)
326
- else:
327
- # No fallback, fail request
328
- status_str = "validation_failed" if "validation_failed" in str(primary_exc) else "failed"
329
- error_msg = str(primary_exc)
330
- latency_ms = (time.time() - start_time) * 1000.0
331
-
332
- background_tasks.add_task(
333
- db_log_request, tenant_id=tenant_id, model=model_req, logical_model=model_req,
334
- prompt_tokens=0, completion_tokens=0, cost_usd=0.0, cache_hit=False, cache_type=None,
335
- primary_backend=primary, selected_backend=selected_backend, fallback_count=fallback_count,
336
- status_str=status_str, error_message=error_msg, queue_ms=0.0, ttft_ms=0.0, latency_ms=latency_ms
337
- )
338
-
339
- REQUESTS_TOTAL.labels(tenant=tenant_id, model=model_req, backend=selected_backend, status=status_str).inc()
340
- await router_engine.record_metrics(selected_backend, 0.0, latency_ms, success=False)
341
-
342
- QUEUE_DEPTH.labels(backend=primary).dec()
343
-
344
- status_code = 422 if status_str == "validation_failed" else 502
345
- raise HTTPException(status_code=status_code, detail=error_msg)
346
-
347
- # Success execution
348
- latency_ms = (time.time() - start_time) * 1000.0
349
- ttft_ms = resp.get("timing", {}).get("ttft_ms", latency_ms)
350
-
351
- # Store in Cache
352
- await cache_layer.store_exact(req, resp)
353
-
354
- # Dec queue depth
355
- QUEUE_DEPTH.labels(backend=selected_backend).dec()
356
-
357
- # Record stats
358
- background_tasks.add_task(
359
- db_log_request,
360
- tenant_id=tenant_id,
361
- model=resp.get("model", model_req),
362
- logical_model=model_req,
363
- prompt_tokens=resp.get("usage", {}).get("prompt_tokens", 0),
364
- completion_tokens=resp.get("usage", {}).get("completion_tokens", 0),
365
- cost_usd=resp.get("usage", {}).get("estimated_cost_usd", 0.0),
366
- cache_hit=False,
367
- cache_type=None,
368
- primary_backend=primary,
369
- selected_backend=selected_backend,
370
- fallback_count=fallback_count,
371
- status_str=status_str,
372
- error_message=None,
373
- queue_ms=0.0,
374
- ttft_ms=ttft_ms,
375
- latency_ms=latency_ms
376
- )
377
-
378
- # Update Prometheus metrics
379
- REQUESTS_TOTAL.labels(tenant=tenant_id, model=model_req, backend=selected_backend, status="completed").inc()
380
- REQUEST_LATENCY.labels(tenant=tenant_id, model=model_req, backend=selected_backend).observe(latency_ms / 1000.0)
381
- TTFT_LATENCY.labels(tenant=tenant_id, model=model_req, backend=selected_backend).observe(ttft_ms / 1000.0)
382
-
383
- # Record to router history
384
- await router_engine.record_metrics(selected_backend, ttft_ms, latency_ms, success=True)
385
-
386
- # Add routing details into standard response metadata
387
- resp["logical_model"] = model_req
388
- resp["route"] = {
389
- "selected_backend": selected_backend,
390
- "fallback_count": fallback_count,
391
- "cache_hit": False,
392
- "policy": req.get("routing", {}).get("policy", "latency")
393
- }
394
- return resp
395
-
396
-
397
- async def handle_streaming_flow(
398
- req: dict[str, Any],
399
- tenant_id: str,
400
- primary: str,
401
- fallback: Optional[str],
402
- background_tasks: BackgroundTasks
403
- ) -> StreamingResponse:
404
- model_req = req.get("model", "edge/auto")
405
-
406
- async def event_generator():
407
- start_time = time.time()
408
- fallback_count = 0
409
- selected_backend = primary
410
-
411
- ttft_ms = 0.0
412
- ttft_recorded = False
413
- accumulated_content = []
414
-
415
- prompt_tokens = 0
416
- completion_tokens = 0
417
- cost_usd = 0.0
418
-
419
- QUEUE_DEPTH.labels(backend=primary).inc()
420
-
421
- try:
422
- # Stream from primary backend
423
- logger.info(f"Streaming from primary backend: {primary}")
424
- async for chunk in ADAPTERS[primary].generate_stream(req):
425
- # Intercept metadata chunk at the end of the stream
426
- if "usage" in chunk:
427
- prompt_tokens = chunk["usage"].get("prompt_tokens", 0)
428
- completion_tokens = chunk["usage"].get("completion_tokens", 0)
429
- cost_usd = chunk["usage"].get("estimated_cost_usd", 0.0)
430
- if "timing" in chunk:
431
- ttft_ms = chunk["timing"].get("ttft_ms", ttft_ms)
432
- continue
433
-
434
- # Record TTFT when first chunk content arrives
435
- choices = chunk.get("choices", [])
436
- if choices and choices[0].get("delta", {}).get("content"):
437
- if not ttft_recorded:
438
- ttft_ms = (time.time() - start_time) * 1000.0
439
- ttft_recorded = True
440
- TTFT_LATENCY.labels(tenant=tenant_id, model=model_req, backend=primary).observe(ttft_ms / 1000.0)
441
- accumulated_content.append(choices[0]["delta"]["content"])
442
-
443
- yield f"data: {json.dumps(chunk, ensure_ascii=False)}\n\n"
444
-
445
- except Exception as primary_exc:
446
- logger.warning(f"Streaming failed on primary backend {primary}: {primary_exc}")
447
-
448
- if fallback:
449
- logger.info(f"Streaming: falling back to {fallback}")
450
- fallback_count += 1
451
- selected_backend = fallback
452
- FALLBACK_TOTAL.labels(from_backend=primary, to_backend=fallback, reason=str(primary_exc)).inc()
453
-
454
- QUEUE_DEPTH.labels(backend=primary).dec()
455
- QUEUE_DEPTH.labels(backend=fallback).inc()
456
-
457
- # Clean accumulator if we restart stream entirely
458
- # Or append a clear boundary
459
- accumulated_content = []
460
- ttft_recorded = False
461
-
462
- try:
463
- async for chunk in ADAPTERS[fallback].generate_stream(req):
464
- if "usage" in chunk:
465
- prompt_tokens = chunk["usage"].get("prompt_tokens", 0)
466
- completion_tokens = chunk["usage"].get("completion_tokens", 0)
467
- cost_usd = chunk["usage"].get("estimated_cost_usd", 0.0)
468
- if "timing" in chunk:
469
- ttft_ms = chunk["timing"].get("ttft_ms", ttft_ms)
470
- continue
471
-
472
- choices = chunk.get("choices", [])
473
- if choices and choices[0].get("delta", {}).get("content"):
474
- if not ttft_recorded:
475
- ttft_ms = (time.time() - start_time) * 1000.0
476
- ttft_recorded = True
477
- TTFT_LATENCY.labels(tenant=tenant_id, model=model_req, backend=fallback).observe(ttft_ms / 1000.0)
478
- accumulated_content.append(choices[0]["delta"]["content"])
479
-
480
- yield f"data: {json.dumps(chunk, ensure_ascii=False)}\n\n"
481
- except Exception as fallback_exc:
482
- logger.error(f"Fallback streaming failed on {fallback}: {fallback_exc}")
483
- latency_ms = (time.time() - start_time) * 1000.0
484
-
485
- background_tasks.add_task(
486
- db_log_request, tenant_id=tenant_id, model=model_req, logical_model=model_req,
487
- prompt_tokens=0, completion_tokens=0, cost_usd=0.0, cache_hit=False, cache_type=None,
488
- primary_backend=primary, selected_backend=selected_backend, fallback_count=fallback_count,
489
- status_str="failed", error_message=str(fallback_exc), queue_ms=0.0, ttft_ms=0.0, latency_ms=latency_ms
490
- )
491
- REQUESTS_TOTAL.labels(tenant=tenant_id, model=model_req, backend=selected_backend, status="failed").inc()
492
- await router_engine.record_metrics(selected_backend, 0.0, latency_ms, success=False)
493
- QUEUE_DEPTH.labels(backend=selected_backend).dec()
494
- yield f"data: {json.dumps({'error': f'Streaming error occurred: {fallback_exc}'})}\n\n"
495
- yield "data: [DONE]\n\n"
496
- return
497
- else:
498
- latency_ms = (time.time() - start_time) * 1000.0
499
- background_tasks.add_task(
500
- db_log_request, tenant_id=tenant_id, model=model_req, logical_model=model_req,
501
- prompt_tokens=0, completion_tokens=0, cost_usd=0.0, cache_hit=False, cache_type=None,
502
- primary_backend=primary, selected_backend=selected_backend, fallback_count=fallback_count,
503
- status_str="failed", error_message=str(primary_exc), queue_ms=0.0, ttft_ms=0.0, latency_ms=latency_ms
504
- )
505
- REQUESTS_TOTAL.labels(tenant=tenant_id, model=model_req, backend=selected_backend, status="failed").inc()
506
- await router_engine.record_metrics(selected_backend, 0.0, latency_ms, success=False)
507
- QUEUE_DEPTH.labels(backend=primary).dec()
508
- yield f"data: {json.dumps({'error': f'Streaming error occurred: {primary_exc}'})}\n\n"
509
- yield "data: [DONE]\n\n"
510
- return
511
-
512
- # Stream finished successfully, perform validation
513
- latency_ms = (time.time() - start_time) * 1000.0
514
- final_text = "".join(accumulated_content)
515
-
516
- # Schema validation check
517
- val_res = validator.validate_stream_chunk(req, final_text)
518
- status_str = "completed"
519
- error_msg = None
520
-
521
- if not val_res.ok:
522
- status_str = "validation_failed"
523
- error_msg = f"Output schema validation failed: {val_res.reason}"
524
- logger.error(error_msg)
525
- yield f"data: {json.dumps({'error': error_msg})}\n\n"
526
- yield "data: [DONE]\n\n"
527
- else:
528
- # Successful validation, Cache results (non-streaming shape)
529
- full_response_shape = {
530
- "id": f"chatcmpl-{uuid.uuid4()}",
531
- "object": "chat.completion",
532
- "created": int(time.time()),
533
- "model": "openai/gpt-4o-mini" if selected_backend == "openai" else "meta-llama/Meta-Llama-3-8B-Instruct",
534
- "choices": [{
535
- "index": 0,
536
- "message": {"role": "assistant", "content": final_text},
537
- "finish_reason": "stop"
538
- }],
539
- "usage": {
540
- "prompt_tokens": prompt_tokens,
541
- "completion_tokens": completion_tokens,
542
- "total_tokens": prompt_tokens + completion_tokens,
543
- "estimated_cost_usd": cost_usd
544
- }
545
- }
546
- await cache_layer.store_exact(req, full_response_shape)
547
-
548
- # Send standard final statistics chunk to client
549
- stats_chunk = {
550
- "id": "edgeserve-stream-end",
551
- "object": "chat.completion.chunk",
552
- "choices": [],
553
- "usage": {
554
- "prompt_tokens": prompt_tokens,
555
- "completion_tokens": completion_tokens,
556
- "total_tokens": prompt_tokens + completion_tokens,
557
- "estimated_cost_usd": cost_usd,
558
- },
559
- "timing": {
560
- "ttft_ms": ttft_ms,
561
- "latency_ms": latency_ms
562
- }
563
- }
564
- yield f"data: {json.dumps(stats_chunk, ensure_ascii=False)}\n\n"
565
- yield "data: [DONE]\n\n"
566
-
567
- # Record stats
568
- background_tasks.add_task(
569
- db_log_request,
570
- tenant_id=tenant_id,
571
- model="openai/gpt-4o-mini" if selected_backend == "openai" else "meta-llama/Meta-Llama-3-8B-Instruct",
572
- logical_model=model_req,
573
- prompt_tokens=prompt_tokens,
574
- completion_tokens=completion_tokens,
575
- cost_usd=cost_usd,
576
- cache_hit=False,
577
- cache_type=None,
578
- primary_backend=primary,
579
- selected_backend=selected_backend,
580
- fallback_count=fallback_count,
581
- status_str=status_str,
582
- error_message=error_msg,
583
- queue_ms=0.0,
584
- ttft_ms=ttft_ms,
585
- latency_ms=latency_ms
586
- )
587
-
588
- REQUESTS_TOTAL.labels(tenant=tenant_id, model=model_req, backend=selected_backend, status=status_str).inc()
589
- REQUEST_LATENCY.labels(tenant=tenant_id, model=model_req, backend=selected_backend).observe(latency_ms / 1000.0)
590
- await router_engine.record_metrics(selected_backend, ttft_ms, latency_ms, success=(status_str == "completed"))
591
-
592
- QUEUE_DEPTH.labels(backend=selected_backend).dec()
593
-
594
- return StreamingResponse(
595
- event_generator(),
596
- media_type="text/event-stream",
597
- headers={"Cache-Control": "no-cache", "Connection": "keep-alive"}
598
- )
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
edgeserve/models.py DELETED
@@ -1,66 +0,0 @@
1
- from datetime import datetime, timezone
2
- import uuid
3
- from sqlalchemy import Column, String, Integer, Float, Boolean, DateTime, Numeric
4
- from sqlalchemy.orm import declarative_base
5
-
6
- Base = declarative_base()
7
-
8
- class RequestLog(Base):
9
- __tablename__ = "request_logs"
10
-
11
- id = Column(String(36), primary_key=True, default=lambda: str(uuid.uuid4()))
12
- tenant_id = Column(String(100), nullable=False, index=True)
13
- model = Column(String(100), nullable=False)
14
- logical_model = Column(String(100), nullable=False)
15
-
16
- # Usage and costing
17
- prompt_tokens = Column(Integer, default=0)
18
- completion_tokens = Column(Integer, default=0)
19
- total_tokens = Column(Integer, default=0)
20
- cost_usd = Column(Float, default=0.0)
21
-
22
- # Caching
23
- cache_hit = Column(Boolean, default=False)
24
- cache_type = Column(String(50), nullable=True) # exact, prefix, semantic
25
-
26
- # Routing
27
- primary_backend = Column(String(50), nullable=False)
28
- selected_backend = Column(String(50), nullable=False)
29
- fallback_count = Column(Integer, default=0)
30
- status = Column(String(50), default="completed") # completed, failed, validation_failed, rate_limited
31
- error_message = Column(String(500), nullable=True)
32
-
33
- # Timing (milliseconds)
34
- timing_queue_ms = Column(Float, default=0.0)
35
- timing_ttft_ms = Column(Float, default=0.0)
36
- timing_latency_ms = Column(Float, default=0.0)
37
-
38
- created_at = Column(DateTime(timezone=True), default=lambda: datetime.now(timezone.utc), index=True)
39
-
40
- def to_dict(self):
41
- return {
42
- "id": self.id,
43
- "tenant_id": self.tenant_id,
44
- "model": self.model,
45
- "logical_model": self.logical_model,
46
- "usage": {
47
- "input_tokens": self.prompt_tokens,
48
- "output_tokens": self.completion_tokens,
49
- "total_tokens": self.total_tokens,
50
- "estimated_cost_usd": self.cost_usd,
51
- },
52
- "route": {
53
- "primary_backend": self.primary_backend,
54
- "selected_backend": self.selected_backend,
55
- "fallback_count": self.fallback_count,
56
- "cache_hit": self.cache_hit,
57
- "cache_type": self.cache_type,
58
- },
59
- "status": self.status,
60
- "timing": {
61
- "queue_ms": self.timing_queue_ms,
62
- "ttft_ms": self.timing_ttft_ms,
63
- "latency_ms": self.timing_latency_ms,
64
- },
65
- "created_at": self.created_at.isoformat() if self.created_at else None
66
- }
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
edgeserve/observability.py DELETED
@@ -1,126 +0,0 @@
1
- import time
2
- import logging
3
- from typing import Optional
4
- from fastapi import FastAPI
5
- from opentelemetry import trace
6
- from opentelemetry.sdk.trace import TracerProvider
7
- from opentelemetry.sdk.trace.export import BatchSpanProcessor
8
- from opentelemetry.sdk.resources import Resource
9
- from opentelemetry.exporter.otlp.proto.grpc.trace_exporter import OTLPSpanExporter
10
- from opentelemetry.instrumentation.fastapi import FastAPIInstrumentor
11
- from prometheus_client import Counter, Histogram, Gauge, generate_latest, CONTENT_TYPE_LATEST
12
- from edgeserve.config import settings
13
-
14
- # Setup logging
15
- logging.basicConfig(level=logging.INFO)
16
- logger = logging.getLogger("edgeserve.observability")
17
-
18
- # --- PROMETHEUS METRICS ---
19
- # Counters
20
- REQUESTS_TOTAL = Counter(
21
- "edgeserve_request_total",
22
- "Total requests routed",
23
- ["tenant", "model", "backend", "status"]
24
- )
25
-
26
- CACHE_HIT_TOTAL = Counter(
27
- "edgeserve_cache_hit_total",
28
- "Total cache hit count",
29
- ["type"] # exact, prefix, semantic
30
- )
31
-
32
- PROVIDER_COST_USD_TOTAL = Counter(
33
- "edgeserve_provider_cost_usd_total",
34
- "Total accumulated token cost in USD",
35
- ["backend", "tenant"]
36
- )
37
-
38
- VALIDATION_FAIL_TOTAL = Counter(
39
- "edgeserve_validation_fail_total",
40
- "Total output validation failures",
41
- ["reason"]
42
- )
43
-
44
- ROUTING_DECISION_TOTAL = Counter(
45
- "edgeserve_routing_decision_total",
46
- "Total routing decisions made",
47
- ["policy", "backend"]
48
- )
49
-
50
- FALLBACK_TOTAL = Counter(
51
- "edgeserve_fallback_total",
52
- "Total fallback occurrences",
53
- ["from_backend", "to_backend", "reason"]
54
- )
55
-
56
- RATE_LIMITED_TOTAL = Counter(
57
- "edgeserve_rate_limited_total",
58
- "Total requests rate limited",
59
- ["scope"] # tenant, global
60
- )
61
-
62
- # Histograms
63
- REQUEST_LATENCY = Histogram(
64
- "edgeserve_request_latency_seconds",
65
- "End-to-end request latency in seconds",
66
- ["tenant", "model", "backend"],
67
- buckets=(0.01, 0.05, 0.1, 0.25, 0.5, 1.0, 2.5, 5.0, 10.0, 30.0)
68
- )
69
-
70
- TTFT_LATENCY = Histogram(
71
- "edgeserve_ttft_seconds",
72
- "Time to first token (TTFT) in seconds",
73
- ["tenant", "model", "backend"],
74
- buckets=(0.01, 0.05, 0.1, 0.25, 0.5, 1.0, 2.5, 5.0, 10.0)
75
- )
76
-
77
- INTER_TOKEN_LATENCY = Histogram(
78
- "edgeserve_inter_token_latency_seconds",
79
- "Inter-token generation latency in seconds",
80
- ["tenant", "model", "backend"],
81
- buckets=(0.005, 0.01, 0.02, 0.05, 0.1, 0.2, 0.5)
82
- )
83
-
84
- # Gauges
85
- QUEUE_DEPTH = Gauge(
86
- "edgeserve_queue_depth",
87
- "Current active scheduling queue depth",
88
- ["backend"]
89
- )
90
-
91
- # --- OPENTELEMETRY SETUP ---
92
- tracer = trace.get_tracer("edgeserve")
93
-
94
- def setup_observability(app: FastAPI) -> None:
95
- """Initialize OpenTelemetry and Prometheus instrumentation."""
96
- try:
97
- # Define Resource attributes
98
- resource = Resource.create(attributes={
99
- "service.name": settings.SERVICE_NAME,
100
- "service.environment": settings.ENV
101
- })
102
-
103
- # Configure TracerProvider
104
- provider = TracerProvider(resource=resource)
105
-
106
- # Configure OTLP Exporter pointing to the OTel Collector
107
- # This will export spans to Jaeger via the collector
108
- otlp_exporter = OTLPSpanExporter(
109
- endpoint=settings.OTEL_EXPORTER_OTLP_ENDPOINT,
110
- insecure=True
111
- )
112
-
113
- span_processor = BatchSpanProcessor(otlp_exporter)
114
- provider.add_span_processor(span_processor)
115
- trace.set_tracer_provider(provider)
116
-
117
- # Instrument FastAPI app
118
- FastAPIInstrumentor.instrument_app(app, tracer_provider=provider)
119
- logger.info("OpenTelemetry instrumentation completed successfully.")
120
-
121
- except Exception as e:
122
- logger.warning(f"Failed to initialize OpenTelemetry tracing: {e}. Running without distributed tracing.")
123
-
124
- def get_metrics_response() -> tuple[bytes, str]:
125
- """Generate formatting compliant with Prometheus scraping protocol."""
126
- return generate_latest(), CONTENT_TYPE_LATEST
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
edgeserve/router.py DELETED
@@ -1,192 +0,0 @@
1
- import json
2
- import logging
3
- from typing import Any, Optional, NamedTuple
4
- from edgeserve.auth import get_redis_client
5
- from edgeserve.observability import ROUTING_DECISION_TOTAL
6
-
7
- logger = logging.getLogger("edgeserve.router")
8
-
9
- # Base baseline performance configurations (used if no dynamic history exists)
10
- BASELINES = {
11
- "vllm": {
12
- "ttft_ms": 150.0,
13
- "p95_ms": 350.0,
14
- "cost_per_token": 0.00001 / 1000, # cheap local amortization
15
- "failure_risk": 0.0,
16
- "cache_bonus": 50.0,
17
- },
18
- "openai": {
19
- "ttft_ms": 250.0,
20
- "p95_ms": 800.0,
21
- "cost_per_token": 0.15 / 1e6, # gpt-4o-mini pricing
22
- "failure_risk": 0.0,
23
- "cache_bonus": 0.0,
24
- }
25
- }
26
-
27
- class BackendScore(NamedTuple):
28
- name: str
29
- score: float
30
- predicted_ttft_ms: float
31
- expected_cost_usd: float
32
- failure_risk: float
33
- reason: str
34
-
35
- class Router:
36
- async def get_backend_stats(self, backend: str) -> dict[str, float]:
37
- """
38
- Retrieves running metrics for a backend from Redis, falling back to static baselines.
39
- """
40
- client = get_redis_client()
41
- if client is None:
42
- return BASELINES[backend]
43
-
44
- try:
45
- # We fetch rolling averages stored in Redis
46
- # In a real system, these would be computed asynchronously or written after each request
47
- ttft_raw = await client.get(f"edgeserve:stats:{backend}:ttft")
48
- p95_raw = await client.get(f"edgeserve:stats:{backend}:p95")
49
- fail_raw = await client.get(f"edgeserve:stats:{backend}:failure_rate")
50
-
51
- stats = BASELINES[backend].copy()
52
- if ttft_raw:
53
- stats["ttft_ms"] = float(ttft_raw)
54
- if p95_raw:
55
- stats["p95_ms"] = float(p95_raw)
56
- if fail_raw:
57
- stats["failure_risk"] = float(fail_raw)
58
-
59
- return stats
60
- except Exception as e:
61
- logger.warning(f"Failed to fetch dynamic stats for {backend}: {e}. Using baselines.")
62
- return BASELINES[backend]
63
-
64
- async def record_metrics(self, backend: str, ttft_ms: float, latency_ms: float, success: bool) -> None:
65
- """
66
- Updates the running metrics for a backend in Redis.
67
- Uses exponential moving average for simplicity.
68
- """
69
- client = get_redis_client()
70
- if client is None:
71
- return
72
-
73
- try:
74
- alpha = 0.2 # EMA smoothing factor
75
-
76
- # Update TTFT
77
- old_ttft = await client.get(f"edgeserve:stats:{backend}:ttft")
78
- new_ttft = ttft_ms if not old_ttft else (alpha * ttft_ms + (1 - alpha) * float(old_ttft))
79
- await client.set(f"edgeserve:stats:{backend}:ttft", str(new_ttft))
80
-
81
- # Update P95
82
- old_p95 = await client.get(f"edgeserve:stats:{backend}:p95")
83
- new_p95 = latency_ms if not old_p95 else (alpha * latency_ms + (1 - alpha) * float(old_p95))
84
- await client.set(f"edgeserve:stats:{backend}:p95", str(new_p95))
85
-
86
- # Update Failure rate (1 for fail, 0 for success)
87
- fail_val = 1.0 if not success else 0.0
88
- old_fail = await client.get(f"edgeserve:stats:{backend}:failure_rate")
89
- new_fail = fail_val if not old_fail else (alpha * fail_val + (1 - alpha) * float(old_fail))
90
- await client.set(f"edgeserve:stats:{backend}:failure_rate", str(new_fail))
91
-
92
- except Exception as e:
93
- logger.error(f"Failed to update Redis metrics for {backend}: {e}")
94
-
95
- async def choose_backend(self, req: dict[str, Any]) -> tuple[str, Optional[str], str]:
96
- """
97
- Evaluates backend options and returns (primary_backend, fallback_backend, reasoning).
98
- Respects hard routing constraints (e.g. routing.allow_local, routing.allow_cloud).
99
- """
100
- model_req = req.get("model", "edge/auto")
101
-
102
- # Hard pin constraints based on requested model name
103
- if model_req in ["gpt-4o-mini", "gpt-4o", "gpt-3.5-turbo"]:
104
- ROUTING_DECISION_TOTAL.labels(policy="hard_pin", backend="openai").inc()
105
- return "openai", None, f"Model pinned to OpenAI: {model_req}"
106
-
107
- if model_req in ["meta-llama/Meta-Llama-3-8B-Instruct", "llama-3-8b"]:
108
- ROUTING_DECISION_TOTAL.labels(policy="hard_pin", backend="vllm").inc()
109
- return "vllm", "openai", f"Model pinned to local vLLM: {model_req}"
110
-
111
- # Parse routing policy options
112
- routing_opts = req.get("routing", {})
113
- allow_local = routing_opts.get("allow_local", True)
114
- allow_cloud = routing_opts.get("allow_cloud", True)
115
- policy = routing_opts.get("policy", "latency") # latency or cost
116
-
117
- candidates = []
118
- if allow_local:
119
- candidates.append("vllm")
120
- if allow_cloud:
121
- candidates.append("openai")
122
-
123
- if not candidates:
124
- # Fallback default if inputs are contradictory
125
- candidates = ["vllm", "openai"]
126
-
127
- if len(candidates) == 1:
128
- selected = candidates[0]
129
- fallback = "openai" if selected == "vllm" else "vllm"
130
- ROUTING_DECISION_TOTAL.labels(policy="single_candidate", backend=selected).inc()
131
- return selected, fallback, f"Only one backend allowed: {selected}"
132
-
133
- # Evaluate weights based on policy
134
- if policy == "cost":
135
- # Cost-focused optimization: heavy weight on cost, moderate on latency
136
- w_ttft = 0.1
137
- w_p95 = 0.1
138
- w_cost = 0.7
139
- w_fail = 0.1
140
- else: # latency
141
- # Latency-focused optimization: heavy weight on TTFT/latency, low on cost
142
- w_ttft = 0.4
143
- w_p95 = 0.3
144
- w_cost = 0.1
145
- w_fail = 0.2
146
-
147
- scores = []
148
- # Estimate request prompt size to forecast cost
149
- prompt_len = sum(len(m.get("content", "")) for m in req.get("messages", []))
150
- input_tokens = prompt_len // 4 + 10
151
- expected_output = req.get("max_output_tokens", 256)
152
-
153
- for backend in candidates:
154
- stats = await self.get_backend_stats(backend)
155
-
156
- # Predict costs
157
- expected_cost = 0.0
158
- if backend == "openai":
159
- prices = BASELINES["openai"]
160
- expected_cost = (input_tokens * prices["cost_per_token"]) + (expected_output * prices["cost_per_token"] * 4)
161
- else: # vllm
162
- prices = BASELINES["vllm"]
163
- expected_cost = (input_tokens * prices["cost_per_token"]) + (expected_output * prices["cost_per_token"] * 1.5)
164
-
165
- # Score function
166
- score_val = (
167
- w_ttft * stats["ttft_ms"]
168
- + w_p95 * stats["p95_ms"]
169
- + w_cost * expected_cost * 100000.0 # Scale cost for comparison
170
- + w_fail * stats["failure_risk"] * 1000.0
171
- - stats["cache_bonus"] # cache bonus reduces score (lower is better)
172
- )
173
-
174
- scores.append(BackendScore(
175
- name=backend,
176
- score=score_val,
177
- predicted_ttft_ms=stats["ttft_ms"],
178
- expected_cost_usd=expected_cost,
179
- failure_risk=stats["failure_risk"],
180
- reason=f"score={score_val:.2f} (ttft={stats['ttft_ms']}ms, cost=${expected_cost:.6f}, fail_risk={stats['failure_risk']})"
181
- ))
182
-
183
- # Sort scores (ascending order: lowest score is the best option)
184
- scores.sort(key=lambda x: x.score)
185
- primary = scores[0].name
186
- fallback = scores[1].name if len(scores) > 1 else None
187
-
188
- ROUTING_DECISION_TOTAL.labels(policy=policy, backend=primary).inc()
189
- reasoning = f"Selected {primary} using policy '{policy}'. Candidates: " + ", ".join(f"{s.name}={s.score:.2f}" for s in scores)
190
- logger.info(f"Router decision: {reasoning}")
191
-
192
- return primary, fallback, reasoning
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
edgeserve/validator.py DELETED
@@ -1,79 +0,0 @@
1
- import json
2
- import logging
3
- from typing import Any, Optional, NamedTuple
4
- from jsonschema import validate, ValidationError
5
- from edgeserve.observability import VALIDATION_FAIL_TOTAL
6
-
7
- logger = logging.getLogger("edgeserve.validator")
8
-
9
- class ValidationResult(NamedTuple):
10
- ok: bool
11
- reason: Optional[str] = None
12
-
13
- class OutputValidator:
14
- def validate_schema(self, content: str, schema: dict[str, Any]) -> ValidationResult:
15
- """
16
- Validates content string parses as JSON and conforms to the specified JSON schema.
17
- """
18
- try:
19
- parsed_json = json.loads(content)
20
- except json.JSONDecodeError as jde:
21
- reason = f"JSON decode error: {jde}"
22
- VALIDATION_FAIL_TOTAL.labels(reason="invalid_json").inc()
23
- return ValidationResult(ok=False, reason=reason)
24
-
25
- try:
26
- validate(instance=parsed_json, schema=schema)
27
- return ValidationResult(ok=True)
28
- except ValidationError as ve:
29
- reason = f"JSON Schema validation error: {ve.message}"
30
- VALIDATION_FAIL_TOTAL.labels(reason="schema_violation").inc()
31
- return ValidationResult(ok=False, reason=reason)
32
-
33
- def validate_response(self, req: dict[str, Any], resp: dict[str, Any]) -> ValidationResult:
34
- """
35
- Validates an LLM response based on the gateway request specifications.
36
- Currently checks JSON schemas.
37
- """
38
- # If no JSON schema is requested, we pass by default
39
- response_format = req.get("response_format")
40
- if not response_format:
41
- return ValidationResult(ok=True)
42
-
43
- fmt_type = response_format.get("type")
44
- if fmt_type != "json_schema":
45
- return ValidationResult(ok=True)
46
-
47
- schema_dict = response_format.get("json_schema", {}).get("schema")
48
- if not schema_dict:
49
- return ValidationResult(ok=True)
50
-
51
- # Extract response text to validate
52
- choices = resp.get("choices", [])
53
- if not choices:
54
- reason = "No choices returned in response to validate."
55
- VALIDATION_FAIL_TOTAL.labels(reason="empty_choices").inc()
56
- return ValidationResult(ok=False, reason=reason)
57
-
58
- content = choices[0].get("message", {}).get("content", "")
59
- if not content:
60
- reason = "Empty content in message choices."
61
- VALIDATION_FAIL_TOTAL.labels(reason="empty_content").inc()
62
- return ValidationResult(ok=False, reason=reason)
63
-
64
- return self.validate_schema(content, schema_dict)
65
-
66
- def validate_stream_chunk(self, req: dict[str, Any], accumulated_content: str) -> ValidationResult:
67
- """
68
- Optional validator for checking partial stream updates.
69
- Allows testing if the final accumulated stream complies.
70
- """
71
- response_format = req.get("response_format")
72
- if not response_format or response_format.get("type") != "json_schema":
73
- return ValidationResult(ok=True)
74
-
75
- schema_dict = response_format.get("json_schema", {}).get("schema")
76
- if not schema_dict:
77
- return ValidationResult(ok=True)
78
-
79
- return self.validate_schema(accumulated_content, schema_dict)
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
update.md ADDED
@@ -0,0 +1,344 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # InferRoute 项目规划报告(LLM 推理网关与控制平面)
2
+
3
+ ## 执行摘要
4
+
5
+ InferRoute 是一个面向大规模语言模型(LLM)推理的网关系统,它为上层应用提供统一的 API 接入,并在多个模型提供商(如 OpenAI、Anthropic、Google 以及自托管开源模型)之间智能路由。设计该系统的主要动机在于 **解决多模型环境下的成本控制、可用性保障和性能优化问题**。如业内专家指出,LLM 网关(LLM Gateway/Proxy/Router)处于应用和底层模型之间,通过单一统一接口提供路由、治理和可观测性。通过集中化的网关,能够实现模型选择、负载均衡、故障切换、速率限制、成本跟踪等功能,将“对 LLM 的调用”转变为可管理、可审计、成本可控和与提供商无关的平台能力。
6
+
7
+ 为实现上述目标,InferRoute 将综合采用**多模型智能路由**策略,根据请求的任务类型、上下文长度、模型特性以及实时性能指标(如延迟、成本估计、可用性)来选择最合适的模型提供商。这样可以显著提高性能和降低成本。例如,通过将摘要任务路由到适合长上下文的模型(如 Claude),TrueFoundry 实验中观察到平均响应时间降低约 20%;而将简单任务路由到小型模型(如 Mixtral)可使耗费的令牌成本减少约 60–70%。综合这些策略,InferRoute 的目标是为多种下游应用场景(如智能客服、文档处理、代码生成、数据抽取等)提供高吞吐、低延迟、高可用且成本可控的 LLM 推理服务。
8
+
9
+ 本报告详细规划了 InferRoute 的目标、用户场景和成功指标,系统架构与数据流,高层路由策略与决策逻辑,关键功能列表(缓存、去重、超时、熔断、重试、降级、可观测性、计费估算、A/B 测试等),实现计划与技术栈建议(后端、数据库、缓存、监控、CI/CD、安全等),测试与基准评估方法(P50/P95/P99、吞吐、成本/请求、故障注入、混合负载),性能目标与基准数据建议,部署与运维策略(多区域、容灾、伸缩),最终交付物清单(README、架构图、API 文档、Demo、benchmark 脚本、可复现实验、监控仪表盘示例等),项目时间线与里程碑,代码组织与模块接口示例,以及示例 API 调用、README/Demo 编写准则和项目在简历/GitHub 上的呈现方式。设计方案以实用工程细节为主,引用了多种官方或权威资料,确保信息准确可靠,便于招聘经理/工程师评估该项目的技术价值和可行性。
10
+
11
+ ## 项目目标与动机
12
+
13
+ 随着 AI 应用对 LLM 的需求爆发,多模型环境下的推理服务成为关键基础设施。传统的单一模型调用已无法满足复杂需求:模型提供商众多,API 形式多样;模型质量、延迟和计费方式差异显著;服务可用性和安全性要求更高。正如专家所指出,**LLM 网关**的出现正是为了解决这一类问题:它置于应用与模型提供商之间,通过统一接口隐藏多源复杂度,并负责路由、治理与可观测。具体来说,InferRoute 的目标包括:
14
+
15
+ - **多模型协同**:支持接入多种 LLM 后端(商业 API 与自部署),使应用无需修改调用逻辑即可灵活选择或动态切换模型。
16
+ - **智能路由决策**:基于任务特征和指标,将请求路由到最佳模型,以达到性能最优、成本最低。例如,将长文本摘要交给长上下文擅长的模型,将简单问答交给快速小模型。
17
+ - **可靠性和高可用**:网关负责自动故障检测与切换,将上游请求在主用模型提供商出现故障或超时情况下平滑切到备用模型。
18
+ - **成本可控**:提供 Token 计费和预算管理。通过限制高成本模型的使用(例如超出预算则降级到低成本模型)来控制整体费用。
19
+ - **治理与合规**:集中执行访问控制、速率限制、策略过滤等,简化安全审计和合规检查。
20
+ - **可观测性**:全链路记录请求的路由决策、模型调用延迟、错误率、Token 用量和成本指标,帮助团队实时监控和优化。
21
+ - **可扩展性和可拓展性**:设计为云原生架构(可部署在 Kubernetes 等平台上),支持横向扩展,并易于集成新模型和自定义策略。
22
+
23
+ 成功建成 InferRoute,将为开发者和企业提供一个企业级的 AI 控制平面,使得 LLM 调用从“零散的API调用”上升为“可管控、可度量、可扩展”的基础服务。这也符合业界给出的部署策略:先实现调用可视化和密钥管理,再逐步添加成本控制和路由故障机制,最终优化缓存和性能路由。
24
+
25
+ ## 目标用户与使用场景
26
+
27
+ InferRoute 面向希望大规模使用 LLM 的公司和开发团队,其典型用户包括 AI 应用开发者、平台团队和 SRE。主要使用场景包括:
28
+
29
+ - **多模型应用**:应用场景需要利用多个模型互补优势,如对话助手将复杂问题路由给 GPT-4,长文档摘要使用 Claude,简单查询使用 Mixtral 等。InferRoute 帮助集中管理这些模型,一键在应用内切换,降低开发复杂度。
30
+ - **任务导向服务**:面向不同业务任务(摘要、分类、代码生成、实体抽取、创意写作等)的智能服务,通过路由策略自动选择最合适模型。例如客服系统自动识别工单类型后选择不同模型处理,提升性能与准确率。
31
+ - **成本敏感的高并发服务**:对于大批量调用场景(如批量文档处理、信息抽取任务),InferRoute 可将高吞吐需求导向廉价模型或本地部署模型,以大幅降低云API成本,同时通过路由规则保证响应质量。
32
+ - **多环境切换与灰度测试**:开发者可以通过 API 标头或路由配置,将部分流量导向新模型版本或灰度环境进行 A/B 测试,实时评估新模型表现。例如传递自定义标头 (如 `X-LLM-Test-Version`) 来启用测试流量。
33
+ - **运维与监控团队**:作为 AI 控制平面,运维团队可通过 InferRoute 获取统一监控视图,包括每个模型后端的延迟、错误率和成本使用情况,便于进行容量规划和故障响应。
34
+
35
+ 在这些场景下,InferRoute 作为一个集中的推理网关与控制平面,将简化后端模型管理、提高系统稳定性,并通过智能路由和监控帮助业务达成性能与成本目标。TrueFoundry 的案例显示,任务型路由和多模型管理能显著提升 ROI:将摘要任务路由到 Claude 可减少 20% 平均延迟,将简单查询路由到 Mixtral 可减少 60-70% 成本,说明路由逻辑对业务影响巨大。
36
+
37
+ ## 成功指标(SLO/SLI)
38
+
39
+ 为衡量 InferRoute 的质量与效果,我们应建立明确的服务级目标(SLO)和可观测指标(SLI):
40
+
41
+ - **延迟指标**:关注首字延迟(Time to First Token, TTFT)和全响应延迟。目标例如**TTFT p50 < 200ms,p95 < 500ms**。根据分析报告,p50 延迟常被夸大,而企业生产环境更关心 p95/p99 延迟。理想情况下,以毫秒级响应为目标,确保大部分请求响应迅速且尾部延迟可控。TTFT直接影响交互体验,而 p95/p99 反映系统在高负载或复杂请求时的表现。
42
+ - **吞吐量**:系统需支持的并发请求量和令牌吞吐。目标要能处理目标场景下的峰值流量(如百级或千级 QPS)而不显著降级。吞吐衡量模型在单位时间内生成的令牌数,好的设计需兼顾高并发请求和单请求吞吐。
43
+ - **可用性/容错**:例如**99.9%** 服务可用性。通过故障转移与重试机制确保在任一模型后端不可用时仍能服务。SLI 可监控接口成功率、错误率,目标将错误率严格控制在可接受范围内(如 <0.1%)。
44
+ - **成本控制**:以**每请求或每千令牌成本**计量。目标根据预算设定,例如每千令牌成本不超过 0.01 美元。路由策略应根据成本预算自动调整模型选择。
45
+ - **缓存命中率**:如果实现 KV 缓存,可衡量缓存命中率和重用比例,以反映性能优化效果。
46
+ - **观察指标**:包括 API 请求速率(TPS)、后端模型调用时延分布(p50/p95/p99)、模型错误率、Token 使用数、成本累积等。所有决策点和关键事件(路由选择、模型切换)都需记录日志和追踪,以便诊断和分析。
47
+ - **其他指标**:如模型健康状态检测周期、重试次数、缓存状态分布等。
48
+
49
+ SLO 设定应依据实际业务场景。例如,对于实时对话应用,TTFT p99 建议小于 1s;对于批处理任务,可接受较高延迟,但吞吐需足够。总之,设计时需格外关注尾部延迟和成本/性能的平衡。
50
+
51
+ ## 系统架构与数据流
52
+
53
+ InferRoute 采用云原生架构,包括**控制平面(Control Plane)**和**数据平面(Data Plane)**两个层次。如 AIBrix 等系统所示,控制平面负责模型元数据管理、策略配置、自动伸缩等,数据平面负责请求分发、负载调度和模型推理执行。总体架构图如下:
54
+
55
+ *图:InferRoute 系统架构示意。系统分为前端 Gateway、控制面组件和后端推理引擎。数据流:客户端请求首先进入统一 API Gateway 进行预处理和鉴权,然后由路由器根据策略选择模型后端并分发请求,推理结果通过网关返回客户端。*
56
+
57
+ - **API Gateway**:对外提供 OpenAI 兼容的统一接口(RESTful)。负责认证鉴权、请求限流、日志采集等。客户端无需感知后端差异,只调用该网关的单一端点。
58
+ - **请求路由器(Router)**:核心组件,依据配置的路由策略和实时指标决定将请求发送至哪个后端(包括 OpenAI、Google、Anthropic API,或本地部署的 vLLM/DynamoPod 等)。路由器可具有**缓存感知**功能(避免对已预置缓存的相同前缀再计算)、**会话关联**策略(同一会话请求倾向路由到缓存存在的 Pod)、以及**多阶段支持**(对预填充/生成分���部署做分段路由)。
59
+ - **模型后端**:实际执行推理的组件。可包括第三方 API 适配层(调用外部商用模型),也可是集群化的自托管引擎(如 vLLM, llama.cpp 等)。每个后端节点可能带有运行时代理(侧车),用于监控状态、上报资源使用、执行请求等。
60
+ - **控制平面服务**:包括模型注册/目录服务、路由规则管理界面、监控指标采集与告警、以及模型自动伸缩器(AutoScaler)等。配置界面允许运维人员定义任务类别、成本预算、SLO 阈值等路由规则。控制平面持续监测各模型健康状况和延迟性能,当检测到异常时可以更新路由或触发熔断。
61
+ - **分布式 KV 缓存**:为提高效率,可设计一个分布式 KV 缓存层,存储最近请求的 KV 缓存(Transformer 前向过程中产生的中间状态)。路由器可以查询缓存状态,优先选择已缓存相同前缀的节点,从而显著减少重复计算。
62
+ - **数据库/存储**:用于保存持久化信息,如模型元数据、路由规则、使用记录、审计日志和前端请求日志。常用关系型数据库(如 PostgreSQL)存储配置和元数据,NoSQL 存储监控数据和日志。
63
+ - **监控和日志系统**:使用 Prometheus/Grafana 等工具收集各组件指标(TPS、延迟、错误率、利用率)和链路跟踪日志(可以使用 OpenTelemetry)。
64
+ - **消息队列(可选)**:为实现异步处理或确保可靠投递,可引入 Kafka/RabbitMQ 等队列,比如用于内部事件(故障通知、指标更新)或批量推理任务。
65
+ - **接口/API 文档**:提供 Swagger/OpenAPI 文档描述网关接口格式、参数说明和示例响应,便于用户使用和二次开发。
66
+
67
+ 以上架构参考了 AIBrix 等开源控制平面(见图和 AIBrix 文档),并结合 LLM 推理特点进行优化。如图所示,控制平面和数据平面协同工作,控制面定义策略和模型图谱,数据面执行请求分发,并通过分布式缓存和并行负载均衡来提升效率。组件之间通过轻量消息和 REST 接口通信,并可容错部署。整体数据流:前端网关接收请求→鉴权限流→Router 读路由配置→根据任务类型/预算/实时状态决策→调用选定后端→后端执行推理→结果返回(顺带计量成本并上报监控)。
68
+
69
+ ## 路由决策逻辑与策略
70
+
71
+ InferRoute 的核心价值在于**智能路由决策**,它综合考虑请求特征和系统指标以最大化性能、成本效益和可用性。主要路由依据包括:
72
+
73
+ - **任务类型路由**:根据请求意图或任务类别(如摘要、分类、编程、实体抽取、创意写作等)将请求定向到最匹配模型。例如,生成性推理和代码相关任务可优先使用 GPT-4 类模型,而长文档摘要使用长上下文模型 Claude,批量标签和简单问答使用快速小型模型。TrueFoundry 建议为每种意图配置合适的模型组合,以优化效果和成本。
74
+ - **上下文长度与成本**:对于输入长度很长的请求,优先考虑支持长上下文的模型。可在路由中设定 Token 预算阈值:如预计令牌使用成本过高,则自动将请求从高成本模型(如 GPT-4)切换到低成本模型(如 Mixtral)。同样可以设置延迟阈值:对延迟敏感的流量(实时对话)设定最大延迟,上限满足不了时切换到更快模型。
75
+ - **实时性能与健康状况**:路由器持续监控各后端的平均延迟、错误率和健康状况。若主用模型出现超时或错误,系统会基于配置的故障恢复策略立即降级到备用模型。TrueFoundry 的动态路由特性允许在每次请求前评估实时指标,满足某些“守护规则”后才发送到首选模型,否则回退到备用。
76
+ - **负载均衡**:对具有相同能力的模型后端,采用平衡算法(如加权轮询、最少连接、延迟打分等)分摊流量。与传统负载均衡不同,LLM 路由需要考虑 KV 缓存分布和硬件差异,避免简单轮询导致性能抖动。
77
+ - **缓存感知调度**:查询或聊天会话通常具有上下文前缀。如果同一前缀已在某个后端节点生成过,可以重用该节点的 KV 缓存,以极低代价完成响应。因此,路由器可维护一个 **数据层** 状态(如哪个 Pod 拥有哪些缓存块),在 **决策层** 中优先选择缓存命中的节点。这可将相同请求的延迟从秒级降到毫秒级。
78
+ - **会话亲和性**:对于多轮对话,保证用户的连续请求落在同一后端节点,以保留 KV 缓存的连续性。这类似传统的会话黏性,但针对 LLM 的缓存状态尤为关键,可显著提升每轮响应速度。
79
+ - **多阶段执行路由**:如果后端部署了“预填充/推理分离”(Prefill/Decode Disaggregation),路由需分两个步骤完成:先将请求发给预填充节点生成 KV 缓存,再将结果转发给解码节点进行生成。执行层协调这两步,实现端到端响应。路由器框架应支持定义多步骤路由策略,而非仅单次转发。
80
+ - **灰度与测试路由**:路由器支持基于请求标头或版本标签的流量切分,用于 A/B 测试或灰度发布。例如,带有特定标头的请求可定向到实验模型,其他请求按常规路由。
81
+ - **会话/租户隔离**:根据域名、路径或用户 ID 进行域级路由,将不同客户或项目的流量隔离开,确保安全和资源划分。
82
+ - **流量优先级**:可为不同的流量类别配置优先级。高优先级流量(如关键对话)可获得更严格的 SLO 和资源,而低优先级流量可在高负载时使用廉价模型。
83
+ - **学习和优化**:路由策略可以基于历史数据不断调整,例如分析不同模型在各类任务上的成功率或延迟分布,自动优化模型选择。监控到趋势变化时(如某模型老化),可以自动下线该模型或减少权重。
84
+
85
+ 下表总结了常见路由策略的特点对比:
86
+
87
+ | 路由策略 | 基础方法 | 特点/应用场景 |
88
+ | ------------------- | ---------------------- | ------------------------------------------ |
89
+ | 固定加权轮询 | 按权重循环分配流量 | 简单稳定,适用于负载均衡,但不考虑请求差异 |
90
+ | 负载感知 | 最少连接、最小延迟 | 优先低延迟后端,提高吞吐;不考虑缓存或任务类型 |
91
+ | 成本/延迟阈值路由 | 基于预算和延迟阈值决策 | 灵活可控,超预算或超时自动切换低成本/低延迟模型 |
92
+ | 任务/意图路由 | 根据任务标签或元数据路由 | 不同任务使用专门模型,提高结果质量和成本效率 |
93
+ | 缓存感知路由 | 优先缓存命中节点 | 减少重复计算,显著降低延迟 |
94
+ | 会话黏性 | 基于用户/会话标识固定路由 | 保持上下文连续性,适用于对话场景 |
95
+ | 混合路由(多层) | 组合以上策略 | 通常结合任务路由+性能阈值+健康检查,实现多维度优化 |
96
+
97
+ 正如 Modular 公司所提倡的,现代 LLM 路由架构分为**数据层、决策层和执行层**。数据层(如缓存状态)须在微秒级更新查询;决策层将多种策略逻辑组合测试;执行层则负责多步骤协调(例如支持分离的预填充与解码流程)。采用这种分层设计可以使路由规则可测试、可复用,并适配各种部署场景。
98
+
99
+ ## 关键功能清单
100
+
101
+ 为了实现上述路由策略和系统目标,InferRoute 需要具备一系列核心功能:
102
+
103
+ - **分布式 KV 缓存**:存储最近会话的 transformer KV 缓存,允许后续前缀相同的请求快速填充。通过全局或按节点共享的缓存(如 Redis、memcached 或自研方案),大幅减少重复计算。
104
+ - **请求去重**:对于并发到来的相同请求,可识别并只执行一次推理,将结果共享给所有等待客户端,避免重复消耗资源。
105
+ - **超时预算**:对每个请求分配超时时间预算,避免单次调用阻塞过久。超时后可中断请求并进行重试或切换备用模型,以提高稳定性。
106
+ - **熔断与重试**:实时监测后端错误率和延迟。若某模型连续失败或超时达到阈值,熔断器将短暂禁用该模型并将流量重路由到其他模型。遇到临时故障时还可自动重试并退避(如指数退避)以平滑故障影响。
107
+ - **降级模式**:在系统过载或部分后端不可用时,自动将高资源任务降级到低精度模型或本地轻量化模型上,以保证可用性。比如在网络连通性不好时切换到本地模型,或紧急时停用缓存以腾出资源。
108
+ - **访问控制与密钥管理**:支持多租户API密钥管理、请求来源鉴权和限流。可为不同租户配置不同的配额和优先级,并在控制台集中管理密钥权限。
109
+ - **速率限制**:基于令牌桶等算法,对外部请求总量或单模型调用频率做限制,防止流量突增导致过载。
110
+ - **路由策略管理界面**:提供动态配置路由规则的界面或 API,包括基于任务标签、延迟阈值、成本预算的规则设置。运营人员可在线修改策略,无需重启服务。
111
+ - **负载均衡**:对相同模型的多实例进行健康检查和流量分发,保持集群内负载均匀。可支持权重调节,以逐步上线/下线模型实例。
112
+ - **监控与可观测性**:集成链路跟踪系统(如 OpenTelemetry),记录每次请求的路由决策和每层调用的延迟。关键事件(例如模型切换、熔断触发)均写入日志。提供实时指标(每模型的延迟分布、错误率、使用量、成本)。通过监控界面和告警确保问题及时发现。表明网关持续监测每个提供者的性能,并记录成本和错误以触发故障恢复。
113
+ - **成本/计费估算**:在调度前评估请求的预估令牌使用量,并结合各模型的计价策略估算成本。可在路由规则中基于预算阈值决策,也可输出成本报告(如每个请求消耗多少美金)。
114
+ - **A/B 测试与灰度发布**:支持流量拆分策略,实现新模型或新策略的灰度发布。可配置按比例路由一部分请求到试验模型,并提供对比指标。TrueFoundry 即使用请求头(如 `X-LLM-Test-Version`)实现了版本切换和流量验证。
115
+ - **扩展插件机制**:允许插入自定义路由器插件(例如自定义 scorer、策略过滤器或自研模型)。模块化设计使得新策略或后端引擎可以插拔式集成。
116
+ - **指标限速与熔断指标**:支持每个模型 TPS(每分钟调用数)、TPM(每分钟令牌数)等指标限制,以实现业务级别的服务质量控制。
117
+ - **身份验证与审计**:集成企业单点登录、LDAP、OAuth 等认证方案;记录谁在何时调用了哪些模型和策略,用于审计合规。
118
+
119
+ 以上功能集合保证了 InferRoute 不仅仅是一个代理层,更是一个面向 LLM 的**服务质量控制平面**。例如 Adnan Masood 提到,LLM 网关的任务包括负载均衡、率限制、成本跟踪、策略执行、日志审计等。InferRoute 聚合这些能力,打造一个可靠、可控、面向生产的推理平台。
120
+
121
+ ## 实现计划与技术栈建议
122
+
123
+ ### 技术栈
124
+
125
+ - **后端服务**:建议使用高性能网络框架,如 Python 的 FastAPI 或 Node.js 的 Express/Koa(若偏好 JS)来实现网关和路由逻辑。FastAPI 具有异步特性,适合高并发场景。
126
+ - **数据库**:使用 PostgreSQL 等关系型数据库存储元数据(模型目录、路由规则、审计日志),并可使用 TimescaleDB 扩展存储时序数据。也可结合 Redis 等键值库存缓存和快速查找。
127
+ - **缓存**:采用 Redis/Memcached 构建分布式缓存层,存储 KV 缓存和路由决策状态。Redis 可用于限流计数、会话粘贴等。
128
+ - **消息队列**:如需处理异步任务(批量推理、事件通知),可以引入 RabbitMQ 或 Kafka。
129
+ - **容器与编排**:使用 Docker 容器化应用,并在 Kubernetes 上部署。Kubernetes 支持滚动更新、自动伸缩、健康检查等,非常适合本项目。可利用现有 KServe/Inferentia 等生态。
130
+ - **监控与日志**:采集应用日志(ELK/EFK)、指标(Prometheus + Grafana)、链路追踪(Jaeger/OpenTelemetry)。利用 Grafana 仪表盘展示模型性能和成本趋势。
131
+ - **API 文档**:使用 Swagger/OpenAPI 自动生成接口文档。便于用户阅读和前端校验。
132
+ - **CI/CD**:使用 GitHub Actions 或 Jenkins 管道实现自动测试、构建和部署。构建镜像后可自动推送到 Docker Registry 并在测试环境部署。实现单元测试和集成测试的自动运行,确保代码质量。
133
+ - **安全**:网关启用 HTTPS/TLS 加密。API 请求带有签名或 Token 验证。敏感配置(API 密钥、密码)使用 Vault/AWS Secrets Manager 等集中管理。遵循最小权限原则,监测异常流量和潜在攻击(可结合 WAF)。
134
+
135
+ ### 实现步骤
136
+
137
+ 1. **需求分析与设计(第1周)**:明确项目功能清单,确定关键 SLO。根据使用场景细化路由策略、缓存与故障处理机制。绘制系统架构草图并选定技术栈。
138
+ 2. **原型搭建(第2周)**:在本地环境下启动一个简单的 FastAPI 服务作为网关框架,实现调用单一模型后端(如 OpenAI API)。验证基本请求转发和响应返回。编写基本单元测试。
139
+ 3. **多模型接入(第3周)**:扩展原型,支持同时调用多个模型提供商(OpenAI、Anthropic 等)。实现模型目录和简单轮询路由,测试不同模型响应。
140
+ 4. **路由逻辑开发(第4周)**:引入任务路由的逻辑分发。实现基于请求元数据(如自定义 Header 指明任务类型)或规则引擎的模型选择。实现延迟/成本阈值控制,初步支持故障切换与重试。
141
+ 5. **缓存与会话(第5周)**:集成 Redis,设计前缀缓存机制。实现 KV 缓存查询和更新,确保路由器能优先选择缓存命中节点。实现会话黏性(Sticky Session)策略,减少跨节点上下文丢失。
142
+ 6. **高级特性(第6周)**:添加超时预算、熔断器、动态速率限制等功能。实现详细监控埋点,集成 Prometheus 导出指标、Jaeger 链路。提供控制面简单 UI/API 来设置路由规则、查看统计。
143
+ 7. **测试与性能优化(第7周)**:编写压力测试脚本(使用 k6/locust 等)模拟真实负载。收集 p50/p95/p99 延迟数据,识别瓶颈并优化(如异步化、连接池、前置缓存等)。确保在并发激增时表现稳定。
144
+ 8. **部署与文档(第8周)**:完善部署脚本和 Kubernetes 配置(包括多区镜像、自动伸缩设置)。撰写 README、架构图、API 文档和使用示例。准备演示环境和测试套件。
145
+ 9. **演示和迭代(第9周)**:使用示例应用(如聊天机器人或知识库问答)进行集成演示。根据反馈微调策略。补充缺失的边界测试,如模型限流下fallback、网络故障恢复等。
146
+ 10. **交付与发布(第10周)**:整理所有成果,发布到 GitHub。包括代码库、文档、示例和基准报告等。编写一份演示视频或演示笔记。最后撰写技术报告或博客,提升项目影响力。
147
+
148
+ **团队建议**:1-3 人开发,跨职能(后端开发、DevOps、测试)。总体迭代周期可安排 8-12 周,根据需求复杂度和人力调整。
149
+
150
+ ## 测试与基准评估方法
151
+
152
+ 为了验证系统性能、稳定性和准确性,需要设计严谨的测试方案:
153
+
154
+ - **负载测试**:使用工具(如 [k6](https://k6.io/)、[Locust](https://locust.io/)、[Vegeta](https://github.com/tsenart/vegeta))在真实请求模式下压测。在负载测试脚本中模拟实际流量分布:并发用户数(50–200+)、请求速率、提示长度分布等。测试时记录各模型后端的 TTFT、生成吞吐、总延迟(TTFT + 解码时间)、系统总体吞吐和资源使用。
155
+ - **尾延迟观测**:重点收集 p50、p95、p99 等百分位延迟数据。确保在高并发和复杂请求场景下,p99 延迟在可接受范围内。关注“P99 问题”,即尾部异常导致的用户体验下降。
156
+ - **成本评估**:对比不同路由策略下单位时间内消耗的 Token 数和实际成本。模拟多种场景(全使用高端模型 vs 智能路由),评估成本节约效果。使用云供应商的计费 API 或第三方工具测量每千令牌花费,验证是否满足预算目标。
157
+ - **故障注入测试**:模拟模型后端故障(如 API 超时、错误频率上升),观察路由器是否按预期进行熔断和降级。可用 [Chaos Engineering](https://chaosengineering.io) 方法,在测试环境故意让某个后端宕机,验证系统能否无缝切换到备用模型而不中断服务。
158
+ - **混合负载**:同时生成短提示和长提示、简单任务与复杂任务混合的流量,测试路由策略的稳健性。检查系统在高负载下是否能根据设置的策略正确分流,并评估资源利用率。
159
+ - **单元与集成测试**:编写单元测试覆盖路由决策逻辑、缓存行为、数据库访问等。集成测试可模拟完整请求流,验证网关与各后端的交互。对异常场景(如超时、响应错误)进行测试,确保正确触发重试和降级逻辑。
160
+ - **基准指标对标**:参考独立基准测试报告了解不同模型提供商或硬件的性能特性,将 InferRoute 在相同条件下的结果与之对比。比如用 [Artificial Analysis](https://artificialanalysis.ai) 等工具对几种模型进行测试,校准自己的负载生成器的准确度。
161
+ - **监控数据分析**:在测试过程中收集 Prometheus 数据,可在 Grafana 中绘制 p50/p95 延迟曲线、吞吐随并发变化曲线、Token 使用率和成本图表,辅助发现性能瓶颈和调优方向。
162
+
163
+ 注重从用户体验角度评估:**TTFT(首字延迟)是聊天交互体验关键**,**p95 和 p99 决定大规模服务质量**。测试结果应明确响应时间分布,以及不同策略下的成本消耗。根据 [GMI Cloud 报告](https://www.gmicloud.ai),真实负载下的 p95 往往远超营销指标,应确保在用户量激增时也能保持稳定性能。
164
+
165
+ ## 性能目标与基准建议
166
+
167
+ 基于上述测试方法,初步的性能目标可以参考行业实践并结合资源规模设定:
168
+
169
+ - **延迟目标**:对于典型提示(100–500 token),尝试将 TTFT p50 控制在 100–200ms,p95 控制在 400–500ms 以下,p99 不超过 1 秒。对于长上下文请求(1000+ token),容忍更高延迟,但应保证 p95 < 2s,否则可考虑拆分或异步策略。
170
+ - **吞吐目标**:针对小模型后端,目标例如单节点能支持数百 QPS;整个系统(多模型并行)在硬件允许下达到上千 QPS。通过缓存和多模型路由,尽量提高整体吞吐。
171
+ - **成本基准**:每千输入+输出令牌成本低于 $0.01(具体依据云厂商定价)。路由策略应将成本高的模型使用量限制在预算内。可参照人工分析(ArtificialAnalysis)或 MLPerf 等公开数据来大致估算不同模型的每令牌成本。
172
+ - **可靠性指标**:在完全正常状态下,系统可用性目标为 ≥99.9%。在单个模型故障时仍能满足基础服务(降级可用),并在几秒级别完成故障切换。
173
+ - **环境基准**:在开发环境和生产环境应运行相同的测试套件,确保延迟和吞吐指标在不同环境一致。在多区域部署时,对比不同机房/云区的延迟差异,优化部署策略(如靠近用户端部署、利用就近实例)。
174
+
175
+ 具体数值须根据实际资源(GPU 型号、网络带宽等)和业务需求微调。上面目标仅供参考,测试时应记录**p50、p95、p99** 等关键统计并与目标对齐。
176
+
177
+ ## 部署与运维
178
+
179
+ - **多区域部署**:建议支持跨多个可用区或地区部署,使用全球负载均衡(如AWS Global Accelerator、GCP Traffic Director)来路由用户请求到最近的区域。每区内部署完整的 InferRoute 服务集群和模型后端实例,实现容灾。跨区可用数据库或异步复制配置确保数据一致性。
180
+ - **自动伸缩**:利用 Kubernetes 的 **Horizontal Pod Autoscaler(HPA)** 和自定义指标(如 CPU、内存、后端队列长度、请求延迟)自动扩缩容。针对 LLM 特性,可采用自定义滑动窗口指标来实时调整副本数。
181
+ - **模型伸缩**:控制平面可以动态在 Kubernetes 中扩容后端模型副本(考虑模型加载时间较长,应预判负载变化)。可以结合 [AIBrix Autoscaler](https://aibrix.readthedocs.io/latest/designs/autoscaling.html)理念,使用 LLM 特定指标来更快地调整容量。
182
+ - **故障恢复**:设计应用故障恢复流程:如果主节点或区域失效,备份节点立即接管。数据库需要多副本、定期备份。关键组件使用 StatefulSet + PVC 或者外部托管数据库以保证持久性。
183
+ - **监控告警**:建立完善的监控告警规则,当延迟或错误率超阈值时自动通知开发团队。例如在 Prometheus 中对 TTFT p95、错误率等设置阈值警报。
184
+ - **运维工具**:提供运维命令行或控制台操作,如手动触发模型 reload、更新路由配置、清空缓存等操作。所有操作都应记录审计日志。
185
+ - **安全与合规**:确保通信加密(TLS)和端点鉴权。按需集成审计工具跟踪敏感操作。利用云平台安全组与网络隔离策略限制访问。
186
+
187
+ 综合而言,部署时要兼顾**性能优化**(靠近 GPU、利用高速缓存)和**弹性保障**(多副本、多区域、自动伸缩)。
188
+
189
+ ## 最终交付物
190
+
191
+ InferRoute 项目完成后,应交付以下成果,以便评估者快速理解和运行系统:
192
+
193
+ - **完整代码仓库**:包含后端服务代码、脚本、配置文件、示例数据。应按模块组织,并带有 README 指引。
194
+ - **架构图**:系统架构图(如上图)应被整理并放入文档,说明各组件之间的关系和数据流。
195
+ - **API 文档**:使用 Swagger/OpenAPI 自动生成接口文档,描述网关提供的所有 API 端点、参数和示例请求/响应。
196
+ - **设计文档**:详细介绍系统各部分设计,包括路由策略决策流程图、缓存逻辑说明、数据库设计等。可使用 MerMaid 等绘制流程图和拓扑图嵌入文档中。
197
+ - **示例代码/演示**:提供示例应用(例如基于聊天或文档处理的 Demo)展示如何调用 InferRoute API,以及多模型路由效果。此示例应简单明了,配以注释和运行指南。
198
+ - **基准测试脚本**:包含负载测试脚本和数据生成工具,用于复现测试结果。可在 README 中说明如何使用 k6/locust 运行测试。
199
+ - **实验结果报告**:记录关键的性能指标(p50/p95/p99 延迟、吞吐、成本等),可附上图表或数据表格展示。
200
+ - **监控仪表盘样例**:若有条件,可提供 Grafana 仪表盘的截图或 JSON 文件,展示系统指标的监控界面示例,如各模型的延迟和错误率趋势图。
201
+ - **部署指南**:详细步骤说明如何在 Kubernetes(或其他环境)部署 InferRoute,包括创建服务、配置 Ingress、安装依赖等。
202
+ - **开发者文档**:指导开发者如何参与二次开发和扩展,包括接口说明、模块划分、贡献指南等。
203
+
204
+ 例如,一个高质量的开源项目 README 通常会包含“项目简介、安装使用指南、架构图示例、功能列表、示例代码、许可证和贡献指南”等内容。我们应借鉴优秀项目的经验,将这些元素整合进去:在 README 顶部放置项目徽标和简要描述,接着快速开始指南和架构总览,在“功能”或“设计”章节中展示关键路由算法和决策流程的可视化图表。同时提供若干代码示例,帮助使用者快速上手。如同示例项目所示,一个好的文档中往往含有架构示意图、代码片段和演示动画,以提高可读性。在项目主页上可以附上 CI/CD 状态徽章、覆盖率徽章,增加项目可信度。
205
+
206
+ 总之,交付物应包括 **完整源代码、文档说明、示例/演示和基准结果**,并组织良好,便于任何评估者克隆、部署和测试这个项目。
207
+
208
+ ## 时间线与里程碑
209
+
210
+ 以下为一个示例的 10 周迭代计划表(1-2 人团队),展示每周主要任务和交付成果:
211
+
212
+ | 周次 | 主要任务 | 预期交付成果 |
213
+ | ---- | ---------------------------------- | -------------------------------------------- |
214
+ | 1 | 需求分析、总体设计、技术选型 | 系统架构图、功能列表、技术方案文档 |
215
+ | 2 | 建立基础 API 网关原型(单模型) | 可运行的基本网关服务代码、单元测试 |
216
+ | 3 | 接入多模型后端,模型目录配置 | 支持多个模型的路由原型、配��示例 |
217
+ | 4 | 实现任务型路由和性能阈值策略 | 路由决策模块、阈值触发逻辑 |
218
+ | 5 | 集成分布式缓存,支持 KV 缓存 | 缓存组件集成、缓存命中示例、前缀缓存验证 |
219
+ | 6 | 熔断器、重试机制和监控埋点 | 熔断器实现、重试逻辑、Prometheus 监控指标埋点 |
220
+ | 7 | 压力测试与优化 | 负载测试脚本、性能调优报告 |
221
+ | 8 | 部署自动化与多区域部署测试 | Kubernetes 配置、自动化部署脚本 |
222
+ | 9 | Demo 演示应用集成与用户文档编写 | 示例应用代码、API 文档、使用手册 |
223
+ | 10 | 收尾、代码评审、发布准备 | 完整项目发布版、演示视频或录制演示 |
224
+
225
+ 根据实际情况,可在每个阶段后进行评审和迭代修正。团队人数若更多,可并行进行后端开发和文档工作。重要里程碑包括:基本路由原型完成(第4周末)、缓存功能完善(第5周末)、性能达标(第7周末)、全功能 Demo (第9周末)。这样可以在有限时间内逐步递增系统能力,并及时发现问题。
226
+
227
+ ## 代码组织与模块接口示例
228
+
229
+ InferRoute 的代码库建议采用模块化结构,如下示例:
230
+
231
+ - `app/`:主应用入口,FastAPI 应用初始化、路由声明。
232
+ - `controllers/`:请求处理逻辑,如调用后端模型、融合前后端逻辑。
233
+ - `router/`:路由决策引擎实现,包含多种策略(权重轮询、缓存优先、阈值控制等)的插件。
234
+ - `models/`:模型元数据定义(模型名称、提供商、参数、资源限额)。
235
+ - `cache/`:缓存层封装,用于存储 KV 缓存和会话信息。
236
+ - `db/`:数据访问层,如连接数据库查询路由规则、使用记录等。
237
+ - `monitoring/`:指标上报和日志工具(Prometheus、OpenTelemetry 集成)。
238
+ - `config/`:配置文件和路由规则定义(可支持 YAML/JSON 格式)。
239
+ - `tests/`:单元和集成测试用例。
240
+
241
+ 示例模块接口(Python 风格):
242
+ ```python
243
+ class InferRouter:
244
+ def __init__(self, config: RouterConfig):
245
+ # 初始化路由器,加载策略和模型列表
246
+ ...
247
+ def route_request(self, request: LLMRequest) -> LLMResponse:
248
+ # 核心方法:根据请求(包含 prompt, metadata, user_id 等)和当前状态(延迟、缓存等)决定哪个模型调用
249
+ ...
250
+ ```
251
+ ```python
252
+ class ModelBackend:
253
+ def __init__(self, name: str, api_key: str, endpoint: str, model_id: str):
254
+ # 每个后端服务的接口封装
255
+ ...
256
+ def infer(self, prompt: str, **kwargs) -> InferenceResult:
257
+ # 调用后端模型 API 或本地推理引擎,返回生成结果
258
+ ...
259
+ ```
260
+ ```python
261
+ class CacheManager:
262
+ def get_cached_prefix(self, prompt_hash: str) -> Optional[CachedState]:
263
+ # 查询是否存在对应前缀的 KV 缓存
264
+ ...
265
+ def store_cache(self, prompt_hash: str, kv_state: CachedState):
266
+ # 存储生成后的 KV 缓存
267
+ ...
268
+ ```
269
+ ```python
270
+ class CircuitBreaker:
271
+ def __init__(self, failure_threshold: int, recovery_time: float):
272
+ # 熔断器参数
273
+ def call(self, func, *args, **kwargs):
274
+ # 包装模型调用,统计失败次数,超阈值时阻止调用并触发熔断
275
+ ...
276
+ ```
277
+ 这些示例说明模块边界和接口职责。各模块应有清晰的输入输出文档,方便测试和扩展。
278
+
279
+ ## 示例 API 请求/响应
280
+
281
+ InferRoute 对外提供类 OpenAI 的接口,示例调用格式:
282
+
283
+ **请求示例**:
284
+ ```
285
+ POST /v1/chat/completions
286
+ Headers:
287
+ Authorization: Bearer {API_KEY}
288
+ Content-Type: application/json
289
+ Body:
290
+ {
291
+ "model": "gpt-4",
292
+ "messages": [{"role": "user", "content": "请将以下中文摘要翻译成英文:..."}],
293
+ "user_id": "user123"
294
+ }
295
+ ```
296
+
297
+ **示例响应**:
298
+ ```json
299
+ {
300
+ "id": "infRouteResp1",
301
+ "model": "gpt-4",
302
+ "choices": [
303
+ {
304
+ "index": 0,
305
+ "message": {"role": "assistant", "content": "Translated summary..."},
306
+ "finish_reason": "stop"
307
+ }
308
+ ],
309
+ "usage": {
310
+ "prompt_tokens": 50,
311
+ "completion_tokens": 20,
312
+ "total_tokens": 70
313
+ }
314
+ }
315
+ ```
316
+ 在请求中可附带自定义 Header(例如 `X-Task-Type: "translation"` 或 `X-LLM-Test-Version`)以指示特殊路由要求。响应中 `usage` 字段报告了消耗的令牌数,可用于成本计算。若发生故障切换,返回的 `model` 字段会标记实际使用的后端(如 `"Mixtral-Instruct"`),同时可在响应中额外提供原路由决策和时间戳等调试信息(通过调试模式开关)。
317
+
318
+ ## README 与示例演示最佳实践
319
+
320
+ 项目的 README 和 Demo 应充分展示系统的价值和易用性。参考优秀仓库的做法,README 应包括:项目简介、架构图、特性列表、安装/使用步骤、代码示例、性能指标展示,以及贡献指南。**示例演示**(可用 Jupyter Notebook 或网页应用)应展示如何调用 InferRoute 接口以及路由效果,例如对同一输入分别使用不同模型的对比结果。架构图和流程图建议用 Mermaid 或 Visio 制作清晰展示,如下所示(使用 MerMaid 语法示意):
321
+ ```mermaid
322
+ flowchart TD
323
+ A[Client 请求] -->|HTTP POST| B[API Gateway]
324
+ B --> C{决策层}
325
+ C -->|路由逻辑| D[模型后端1]
326
+ C -->|路由逻辑| E[模型后端2]
327
+ D & E --> F[推理执行]
328
+ F --> B
329
+ B --> A
330
+ ```
331
+ README 中应当附带该类示意图,配以文字说明,以帮助新用户快速理解。示例代码块应覆盖核心用例(如普通问答、长文本摘要、多模型对比)。并且,使用 Markdown 的清晰格式和缩进,保持段落简洁(每段 3-4 行),使用列表强调要点。同时,尽量在文档中提供实时可点击的“运行示例”(如使用 Binder 或 GitHub Codespaces)以增强吸引力。
332
+
333
+ ## 简历/GitHub 展示
334
+
335
+ 若将 InferRoute 项目放在简历或 GitHub 上,应突出项目的技术亮点和成果:
336
+ - 强调 **项目规模和角色**:如“开发了一个支持多模型智能路由的 LLM 推理网关”。
337
+ - 指出 **主要功能实现**:例如“实现了基于任务类型和预算的动态路由策略、分布式 KV 缓存和故障转移机制”。
338
+ - 用 **量化指标** 来体现效果:如“通过路由优化,响应延迟降低 20%,推理成本减少 60%”。引用类似的数据可以帮助说明项目价值。
339
+ - 展示 **技术栈**:FastAPI, Redis, PostgreSQL, Kubernetes, Prometheus, Docker 等,表明熟悉工具链。
340
+ - 如果可能,提供链接到项目的 README, Demo 和架构图截图。在简历中使用简洁语言介绍项目目标和贡献;在 GitHub 项目首页用清晰易读的 README 说明整个系统架构和使用示例。比如写道:“在该项目中,我实现了一个企业级 LLM 路由平台,支持多模型负载均衡和智能降级,显著提升了服务的可靠性和性价比。”
341
+
342
+ 通过上述方式,在简历和代码仓库中突出项目的工程实现细节和影响力,可以让招聘人员/评审快速理解并认可项目的技术深度和实用价值。
343
+
344
+ **参考文献:** 引用了多篇业内文章和开源项目资料,包括 LLM 网关设计原则、多模型路由案例、缓存和故障处理方案以及开源项目 README 编写指南等,以确保设计思路符合当前最佳实践。