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

本机接口、容量预算和 PDF/TXT 检索

PYTHONCPython 3.12.14、OpenAI SDK 3.46.0、PDFium 5.15.2、SQLite 3.53.1;实际环回 HTTP 和本机文件。deployment_lab.py
deployment_lab.py227 行
"""Run local API contracts, capacity calculations and PDF/TXT retrieval."""
from contextlib import closing, contextmanager
from decimal import Decimal
from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer
from importlib.metadata import version
import json
from pathlib import Path
import re
import sqlite3
from threading import Thread
from urllib.error import HTTPError
from urllib.request import ProxyHandler, Request, build_opener



MODEL = "archive-fixture-v1"
OLLAMA_MODEL = "archive:fixture"
PDF_SENTENCE = "Archive boxes are stored on shelf B7."
TEXT_SAMPLE = "The archive closes at 17:00.\nVisitors sign in at reception.\n"


def sample_pdf():
    stream = f"BT /F1 14 Tf 30 150 Td ({PDF_SENTENCE}) Tj ET".encode("ascii")
    objects = [
        b"<< /Type /Catalog /Pages 2 0 R >>",
        b"<< /Type /Pages /Kids [3 0 R] /Count 1 >>",
        b"<< /Type /Page /Parent 2 0 R /MediaBox [0 0 360 200] /Resources << /Font << /F1 4 0 R >> >> /Contents 5 0 R >>",
        b"<< /Type /Font /Subtype /Type1 /BaseFont /Helvetica >>",
        f"<< /Length {len(stream)} >>\nstream\n".encode("ascii") + stream + b"\nendstream",
    ]
    pdf = bytearray(b"%PDF-1.4\n")
    offsets = []
    for index, body in enumerate(objects, 1):
        offsets.append(len(pdf))
        pdf.extend(f"{index} 0 obj\n".encode("ascii") + body + b"\nendobj\n")
    xref = len(pdf)
    pdf.extend(b"xref\n0 6\n0000000000 65535 f \n")
    for offset in offsets:
        pdf.extend(f"{offset:010d} 00000 n \n".encode("ascii"))
    pdf.extend(f"trailer\n<< /Size 6 /Root 1 0 R >>\nstartxref\n{xref}\n%%EOF\n".encode("ascii"))
    return bytes(pdf)


class ApiFixture(BaseHTTPRequestHandler):
    def log_message(self, format, *args):
        pass

    def reply(self, status, body):
        raw = json.dumps(body, ensure_ascii=False).encode()
        self.send_response(status)
        self.send_header("Content-Type", "application/json; charset=utf-8")
        self.send_header("Content-Length", str(len(raw)))
        self.end_headers()
        self.wfile.write(raw)

    def do_GET(self):
        if self.path == "/v1/models":
            return self.reply(200, {"object": "list", "data": [
                {"id": MODEL, "object": "model", "created": 0, "owned_by": "mbsky-fixture"},
            ]})
        self.reply(404, {"error": "unknown route"})

    def do_POST(self):
        if self.path not in ("/api/generate", "/api/chat", "/v1/chat/completions"):
            return self.reply(404, {"error": "unknown route"})
        payload = json.loads(self.rfile.read(int(self.headers["Content-Length"])))
        compatible = self.path.startswith("/v1/")
        if payload.get("model") != (MODEL if compatible else OLLAMA_MODEL):
            return self.reply(404, {"error": {"message": "model not in fixture catalog"}})
        if payload.get("stream", False):
            return self.reply(400, {"error": {"message": "fixture requires stream=false"}})
        if self.path == "/api/generate":
            response = "B7" if payload.get("prompt") == "Where are the boxes?" else "UNKNOWN"
            return self.reply(200, {"response": response, "done": True})
        history = [(message["role"], message["content"]) for message in payload["messages"]]
        answer = "B7" if history == [
            ("user", "Remember shelf B7"), ("assistant", "Noted"), ("user", "Which shelf?")
        ] else "UNKNOWN"
        message = {"role": "assistant", "content": answer}
        if compatible:
            return self.reply(200, {"id": "fixture-response", "object": "chat.completion",
                "created": 0, "model": MODEL, "choices": [
                    {"index": 0, "message": message, "finish_reason": "stop"}]})
        self.reply(200, {"message": message, "done": True})


@contextmanager
def fixture_server():
    with ThreadingHTTPServer(("127.0.0.1", 0), ApiFixture) as server:
        thread = Thread(target=server.serve_forever)
        thread.start()
        try:
            yield f"http://127.0.0.1:{server.server_port}"
        finally:
            server.shutdown()
            thread.join()


def request_json(host, path, payload):
    request = Request(host + path, json.dumps(payload).encode(), {"Content-Type": "application/json"})
    opener = build_opener(ProxyHandler({}))
    try:
        response = opener.open(request, timeout=5)
    except HTTPError as error:
        response = error
    with response:
        return response.status, json.load(response)


def weights_gb(parameters_in_billions, nominal_bits):
    return Decimal(parameters_in_billions) * Decimal(nominal_bits) / 8


def kv_cache_mib(layers, context, kv_heads, head_size, bytes_per_value):
    return layers * context * kv_heads * head_size * 2 * bytes_per_value // (1024 ** 2)


def modelfile_parameters(path):
    # Validate only the five directives used in the two supplied profiles.
    bounds = {"num_ctx": (int, 1, None), "num_predict": (int, 1, None),
              "temperature": (float, 0, None), "top_k": (int, 1, None),
              "top_p": (float, 0, 1)}
    values = {}
    for line in path.read_text(encoding="utf8").splitlines():
        if not line.startswith("PARAMETER "):
            continue
        _, name, literal = line.split()
        convert, low, high = bounds[name]
        value = convert(literal)
        if name in values or not value >= low or (high is not None and value > high):
            raise ValueError(name)
        values[name] = value
    if values.keys() != bounds.keys():
        raise ValueError("profile is incomplete")
    return values


def local_documents(folder):
    import pypdfium2 as pdfium

    text = (folder / "archive-hours.txt").read_text(encoding="utf8")
    records = [("archive-hours.txt", index, line)
               for index, line in enumerate(text.splitlines(), 1) if line.strip()]
    with pdfium.PdfDocument(folder / "archive-shelves.pdf") as pdf:
        for index, page in enumerate(pdf, 1):
            with closing(page), closing(page.get_textpage()) as page_text:
                raw = page_text.get_text_range()
            records.extend(("archive-shelves.pdf", index, line)
                           for line in raw.splitlines() if line.strip())
    return records


def retrieve(path, query):
    words = re.findall(r"[a-z0-9]+", query.lower())
    if not words:
        return None
    search = " AND ".join(words)
    with closing(sqlite3.connect(path)) as db:
        row = db.execute(
            "SELECT source, locator, body FROM chunks WHERE chunks MATCH ? ORDER BY bm25(chunks), rowid LIMIT 1",
            (search,),
        ).fetchone()
    return list(row) if row else None


def exercise(checks, workspace):
    import httpx2
    from openai import NotFoundError, OpenAI

    root = Path(__file__).resolve().parent
    history = [{"role": role, "content": content} for role, content in (
        ("user", "Remember shelf B7"), ("assistant", "Noted"), ("user", "Which shelf?"))]
    with fixture_server() as host:
        status, data = request_json(host, "/api/generate", {
            "model": OLLAMA_MODEL, "prompt": "Where are the boxes?", "stream": False})
        checks.expect("deploy_generate_fixture", "Where are the boxes?", "Send a real loopback POST", [200, "B7", True],
              [status, data["response"], data["done"]])
        for messages, expected in ((history, "B7"), (history[-1:], "UNKNOWN")):
            status, data = request_json(host, "/api/chat", {
                "model": OLLAMA_MODEL, "messages": messages, "stream": False})
            checks.expect(f"deploy_history_{len(messages)}", messages, "Send explicit history over loopback",
                  [200, expected, True], [status, data["message"]["content"], data["done"]])
        with OpenAI(base_url=host + "/v1", api_key="local-fixture", max_retries=0,
                    http_client=httpx2.Client(trust_env=False)) as sdk:
            model_id = sdk.models.list().data[0].id
            answer = sdk.chat.completions.create(model=model_id, messages=history, stream=False)
            checks.expect("deploy_compatible_chat", history, "List model IDs then post with the installed SDK",
                  [MODEL, "B7"], [answer.model, answer.choices[0].message.content])
            try:
                sdk.chat.completions.create(model="wrong-fixture-id", messages=history, stream=False)
            except NotFoundError as error:
                checks.expect("deploy_compatible_wrong_id", "wrong-fixture-id", "Send an unlisted model ID",
                      404, error.status_code)
            else:
                raise AssertionError("An unlisted model ID was accepted")

    estimates = [[str(weights_gb(size, bits)) for bits in (16, 4)] for size in (7, 13, 33, 70)]
    checks.expect("deploy_weights_budget", [7, 13, 33, 70], "Compute ideal FP16 and 4-bit weight-only GB",
          [["14", "3.5"], ["26", "6.5"], ["66", "16.5"], ["140", "35"]], estimates)
    checks.expect("deploy_kv_budget", [4096, 8192], "Compute one-sequence KV MiB under fixed layer and head dimensions",
          [512, 1024], [kv_cache_mib(32, size, 8, 128, 2) for size in (4096, 8192)])
    profiles = [modelfile_parameters(root / name) for name in ("Modelfile.focused", "Modelfile.explore")]
    checks.expect("deploy_modelfile_profiles", ["focused", "explore"],
          "Read and validate the supplied profile values without calling Ollama create",
          [[4096, 96, .2, 20, .85], [8192, 192, .65, 40, .95]],
          [[profile[name] for name in ("num_ctx", "num_predict", "temperature", "top_k", "top_p")] for profile in profiles])
    path = workspace / "archive.sqlite"
    records = local_documents(root)
    with closing(sqlite3.connect(path)) as db, db:
        db.execute("CREATE VIRTUAL TABLE chunks USING fts5(source UNINDEXED, locator UNINDEXED, body)")
        db.executemany("INSERT INTO chunks VALUES (?, ?, ?)", records)
    checks.expect("deploy_pdf_retrieval", "boxes shelf", "Extract PDF text then reopen the SQLite index and retrieve",
          ["archive-shelves.pdf", 1, PDF_SENTENCE], retrieve(path, "boxes shelf"))
    checks.expect("deploy_txt_retrieval", "archive closes", "Reopen the index and retrieve a TXT citation",
          ["archive-hours.txt", 1, TEXT_SAMPLE.splitlines()[0]], retrieve(path, "archive closes"))
    checks.expect("deploy_unknown", "holiday schedule", "Leave missing evidence unresolved", None,
          retrieve(path, "holiday schedule"))
    checks.expect("deploy_runtime_versions", "installed packages", "Read actual SDK, PDF parser and SQLite versions",
          ["3.46.0", "2.16.0", "5.15.2", "3.53.1"],
          [version("openai"), version("httpx2"), version("pypdfium2"), sqlite3.sqlite_version])


if __name__ == "__main__":
    from lab_tools import run_exercise

    run_exercise(exercise)
本例需在 CPython 3.12.14、OpenAI SDK 3.46.0、PDFium 5.15.2、SQLite 3.53.1;实际环回 HTTP 和本机文件。 中运行,请复制源码、保存文件或下载工程包后在本地执行验证。
运行说明与环境独立工程

运行环境:CPython 3.12.14、OpenAI SDK 3.46.0、PDFium 5.15.2、SQLite 3.53.1;实际环回 HTTP 和本机文件。

入口文件:projects/ai-local-deployment/deployment_lab.py

本地运行步骤快速上手
  1. 点击上方“保存源码”保存为 deployment_lab.py,或下载右侧课程工程包。
  2. 确认本地已准备 CPython 3.12.14、OpenAI SDK 3.46.0、PDFium 5.15.2、SQLite 3.53.1;实际环回 HTTP 和本机文件。。
  3. 按对应章节命令执行,结合正文核对实际输出。
附件与关联工程包下载

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

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

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

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

搜索教程、工具与资讯

热门搜索

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

欢迎登录蓝色天空网

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