蓝色天空.知识 · 实践 · 创造
我的收藏
在线代码实验室

验证本站推理网关的 HTTP 和流式合同

PYTHONCPython 3.12.14、FastAPI 0.162.2、Uvicorn 0.54.0、OpenAI SDK 3.46.0、Prometheus client 0.26.0、SciPy 1.18.1。本机回环与固定样本。gateway_lab.py
gateway_lab.py208 行
"""Run an isolated FastAPI streaming and metrics contract over loopback."""
import asyncio
from collections import defaultdict
from contextlib import contextmanager
import hmac
from http.client import HTTPConnection
from importlib.metadata import version
import json
from secrets import token_urlsafe
import socket
from threading import Thread
from time import monotonic, sleep
from typing import Literal

from fastapi import FastAPI, Header, HTTPException
from fastapi.responses import Response, StreamingResponse
from openai import OpenAI
from prometheus_client import CollectorRegistry, Counter, Histogram, generate_latest
from prometheus_client.parser import text_string_to_metric_families
from pydantic import BaseModel, Field
from uvicorn import Config, Server

from lab_tools import run_exercise


class Message(BaseModel):
    role: Literal["system", "user", "assistant"]
    content: str = Field(min_length=1,max_length=180)


class Chat(BaseModel):
    model: str
    messages: list[Message] = Field(min_length=1,max_length=8)
    max_tokens: int = Field(default=8,ge=1,le=8)
    stream: bool = False


def make_app(keys, maximum=2):
    app = FastAPI(docs_url=None,redoc_url=None)
    counts = defaultdict(int)
    registry = CollectorRegistry()
    requests = Counter("archive_demo_requests_total","Accepted and rejected fixture requests",
                       ("status",),registry=registry)
    first_fragment = Histogram("archive_demo_first_fragment_seconds","Time to first fixture fragment",
                               registry=registry)
    state = {"ready": False}

    def require(authorization):
        for name,key in keys.items():
            if authorization and hmac.compare_digest(authorization, "Bearer "+key):
                return name
        raise HTTPException(401,"unauthorized",headers={"WWW-Authenticate":"Bearer"})

    @app.get("/livez")
    def live():
        return {"status":"live"}

    @app.get("/readyz")
    def ready():
        return Response(status_code=200 if state["ready"] else 503)

    @app.get("/metrics")
    def metrics():
        return Response(generate_latest(registry),media_type="text/plain; version=0.0.4; charset=utf-8")

    @app.get("/v1/models")
    def models(authorization: str | None = Header(default=None)):
        require(authorization)
        return {"object":"list","data":[{"id":"archive-fixture","object":"model","created":0,"owned_by":"local"}]}

    @app.post("/v1/chat/completions")
    async def chat(request: Chat, authorization: str | None = Header(default=None)):
        actor = require(authorization)
        if not state["ready"]:
            raise HTTPException(503,"fixture is warming")
        if request.model!="archive-fixture":
            raise HTTPException(404,"unknown model")
        if counts[actor]>=maximum:
            requests.labels("429").inc()
            raise HTTPException(429,"quota exhausted",headers={"Retry-After":"1"})
        counts[actor]+=1
        requests.labels("200").inc()
        words = ["档案","已找到"][:request.max_tokens]
        common = {"id":"chatcmpl-local","model":request.model,"created":0}
        if not request.stream:
            return {**common,"object":"chat.completion","choices":[{"index":0,"finish_reason":"stop",
                "message":{"role":"assistant","content":"".join(words)}}]}
        begin = monotonic()

        async def events():
            for index,part in enumerate(words):
                if index==0:
                    first_fragment.observe(monotonic()-begin)
                chunk = {**common,"object":"chat.completion.chunk","choices":[{"index":0,
                    "delta":{"content":part},"finish_reason":None}]}
                yield f"data: {json.dumps(chunk)}\n\n"
                await asyncio.sleep(0.02)
            final = {**common,"object":"chat.completion.chunk","choices":[{"index":0,
                "delta":{},"finish_reason":"stop"}]}
            yield f"data: {json.dumps(final)}\n\ndata: [DONE]\n\n"
        return StreamingResponse(events(),media_type="text/event-stream",
                                 headers={"Cache-Control":"no-cache"})
    return app, state


@contextmanager
def loopback(app):
    with socket.create_server(("127.0.0.1",0)) as listener:
        port = listener.getsockname()[1]
        server = Server(Config(app,host="127.0.0.1",loop="asyncio",http="h11",ws="none",
                               log_level="critical",access_log=False,timeout_graceful_shutdown=2))
        thread = Thread(target=server.run,kwargs={"sockets":[listener]},daemon=True)
        thread.start()
        try:
            deadline = monotonic()+5
            while not server.started:
                if monotonic()>=deadline or not thread.is_alive():
                    raise RuntimeError("local service did not start")
                sleep(0.01)
            yield port
        finally:
            server.should_exit = True
            thread.join(timeout=6)
            if thread.is_alive():
                raise RuntimeError("local service did not stop")


def get(port,path,key=None):
    conn = HTTPConnection("127.0.0.1",port,timeout=5)
    headers = {"Authorization":"Bearer "+key} if key else {}
    try:
        conn.request("GET",path,headers=headers)
        reply = conn.getresponse()
        return reply.status,reply.read()
    finally:
        conn.close()


def post(port,payload,key=None):
    conn = HTTPConnection("127.0.0.1",port,timeout=5)
    headers = {"Content-Type":"application/json"}
    if key is not None:
        headers["Authorization"]="Bearer "+key
    try:
        conn.request("POST","/v1/chat/completions",body=json.dumps(payload).encode(),headers=headers)
        reply = conn.getresponse()
        return reply.status,json.loads(reply.read()),reply.getheader("Retry-After")
    finally:
        conn.close()


def exercise(checks,_):
    tokens = {actor:token_urlsafe() for actor in ("local-a","local-b")}
    app,state = make_app(tokens)
    request = {"model":"archive-fixture","messages":[{"role":"user","content":"核对档案"}]}
    a,b = tokens.values()
    with loopback(app) as port:
        warming = [get(port,path)[0] for path in ("/livez","/readyz")]
        warming_request = post(port,request,a)[0]
        state["ready"] = True
        ready = get(port,"/readyz")[0]
        checks.expect("deploy_eng_probes",["startup","ready"],
                      "Read liveness and readiness on a real ephemeral loopback service",
                      [[200,503],503,200],[warming,warming_request,ready])

        anonymous = post(port,request)[0]
        unknown = post(port,dict(request,model="absent"),a)[0]
        invalid = post(port,dict(request,max_tokens=0),a)[0]
        valid = post(port,dict(request,max_tokens=1),a)
        catalog = json.loads(get(port,"/v1/models",a)[1])
        checks.expect("deploy_eng_http",[None,"absent",0,1],"Verify auth, unknown model, input validation, truncation and model listing",
                      [401,404,422,200,"档案","archive-fixture"],
                      [anonymous,unknown,invalid,valid[0],valid[1]["choices"][0]["message"]["content"],catalog["data"][0]["id"]])

        begin = monotonic()
        with OpenAI(api_key=a,base_url=f"http://127.0.0.1:{port}/v1",max_retries=0,timeout=5) as client:
            stream = client.chat.completions.create(**request,stream=True)
            with stream:
                first = next(stream)
                first_arrival = monotonic()
                rest = list(stream)
        parts = [event.choices[0].delta.content for event in [first,*rest]]
        checks.expect("deploy_eng_sdk_stream","OpenAI SDK, local SSE",
                      "Consume first content event before EOF, then verify second event and finish reason",
                      [["档案","已找到",None],"stop",True],
                      [parts,rest[-1].choices[0].finish_reason,begin<first_arrival<monotonic()])
        limited = post(port,request,a)
        separate = post(port,request,b)
        checks.expect("deploy_eng_quota","two isolated identities","Verify 429 retry header and another identity's budget",
                      [429,"1",200],[limited[0],limited[2],separate[0]])

        status,body = get(port,"/metrics")
        samples = { (sample.name,tuple(sorted(sample.labels.items()))):sample.value
                    for family in text_string_to_metric_families(body.decode()) for sample in family.samples }
        checks.expect("deploy_eng_metrics","HTTP /metrics","Parse actual exporter counters and first-fragment histogram",
                      [200,3.,1.,1.,True],
                      [status,samples[("archive_demo_requests_total",(("status","200"),))],
                       samples[("archive_demo_requests_total",(("status","429"),))],
                       samples[("archive_demo_first_fragment_seconds_count",())],
                       samples[("archive_demo_first_fragment_seconds_sum",())]>=0])
    libraries=["fastapi","uvicorn","openai","prometheus_client"]
    actual=[version(name) for name in libraries]
    checks.expect("deploy_eng_versions",libraries,"Identify installed local runtime versions",["0.162.2","0.54.0","3.46.0","0.26.0"],actual)


if __name__=="__main__":
    run_exercise(exercise)
本例需在 CPython 3.12.14、FastAPI 0.162.2、Uvicorn 0.54.0、OpenAI SDK 3.46.0、Prometheus client 0.26.0、SciPy 1.18.1。本机回环与固定样本。 中运行,请复制源码、保存文件或下载工程包后在本地执行验证。
运行说明与环境独立工程

运行环境:CPython 3.12.14、FastAPI 0.162.2、Uvicorn 0.54.0、OpenAI SDK 3.46.0、Prometheus client 0.26.0、SciPy 1.18.1。本机回环与固定样本。

入口文件:projects/ai-engineering-deployment/gateway_lab.py

本地运行步骤快速上手
  1. 点击上方“保存源码”保存为 gateway_lab.py,或下载右侧课程工程包。
  2. 确认本地已准备 CPython 3.12.14、FastAPI 0.162.2、Uvicorn 0.54.0、OpenAI SDK 3.46.0、Prometheus client 0.26.0、SciPy 1.18.1。本机回环与固定样本。。
  3. 按对应章节命令执行,结合正文核对实际输出。
附件与关联工程包下载

下载课程关联工程包:AI(人工智能)

课程关联工程包(登记关联30章) · 含当前章节或实例 · mbskycom202612a5.zip

下载课程关联工程包:AI(人工智能)

课程关联工程包(登记关联1章) · 含当前章节或实例 · mbskycom202612a8.zip
SITE SEARCH

搜索教程、工具与资讯

热门搜索

JavaScriptJSON格式化正则表达式AI 编程AI 翻译AI导航专题标签
Esc 关闭

欢迎登录蓝色天空网

使用会员账号,继续你的学习