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

运行费用计算与环回 HTTP 契约

PYTHONPython 3.12.14;环回 HTTP 样本、十进制计算,独立 Ollama 0.40.15 CPU 服务。industry_lab.py
industry_lab.py104 行
"""Test transparent cost units and the real HTTP boundary on localhost."""
from decimal import Decimal
from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer
import json
from threading import Thread
from urllib.error import HTTPError
from urllib.request import ProxyHandler, Request, build_opener

from lab_tools import run_exercise


def daily_price(calls, input_tokens, output_tokens, input_rate, output_rate):
    rates = Decimal(input_rate), Decimal(output_rate)
    return Decimal(calls) * (input_tokens * rates[0] + output_tokens * rates[1]) / 1_000_000


def weights_only(parameters_billions, bits):
    return Decimal(parameters_billions) * bits / 8


def post(address, route, payload):
    request = Request(address + route, json.dumps(payload).encode(), {"Content-Type": "application/json"}, method="POST")
    with build_opener(ProxyHandler({})).open(request, timeout=3) as response:
        return json.loads(response.read())


def exercise(checks, workspace):
    expect = checks.expect
    prices = ["5", "15"]
    traffic = [[800, 200], [1000, 0], [0, 1000], [1000, 1000]]
    daily = [daily_price(100_000, a, b, *prices) for a, b in traffic]
    expect("industry_cost_units", dict(calls=100_000, token_splits=traffic, rates=prices),
           "Apply historical illustrative dollars per million tokens to input and output separately",
           ["700", "500", "1500", "2000"], [str(value) for value in daily])
    expect("industry_cost_period", [800, 200, 30], "Multiply one specified split by 30 days", "21000", str(daily[0] * 30))
    sizes = [[7, 16], [13, 4], [70, 8]]
    expect("industry_weights_only", sizes, "Calculate weights-only GB without including KV or runtime allocations",
           ["14", "6.5", "70"], [str(weights_only(n, bits)) for n, bits in sizes])
    request_log = []

    class Fixture(BaseHTTPRequestHandler):
        def log_message(self, *_):
            return

        def do_POST(self):
            payload = json.loads(self.rfile.read(int(self.headers["Content-Length"])))
            request_log.append([self.path, payload])
            model = payload.get("model")
            if model not in {"lab-a", "lab-b", "lab-c"}:
                status, reply = 404, {"error": "local model fixture unavailable"}
            elif self.path == "/api/generate":
                status, reply = 200, {"response": f"{model} fixed reply", "done": True}
            elif self.path == "/api/chat":
                status, reply = 200, {"message": {"role": "assistant", "content": f"turn {payload['messages'][-1]['content']}"},
                                      "done": True}
            else:
                status, reply = 404, {"error": "unknown path"}
            body = json.dumps(reply).encode()
            self.send_response(status)
            self.send_header("Content-Type", "application/json")
            self.send_header("Content-Length", str(len(body)))
            self.end_headers()
            self.wfile.write(body)

    with ThreadingHTTPServer(("127.0.0.1", 0), Fixture) as server:
        worker = Thread(target=server.serve_forever, daemon=True)
        worker.start()
        address = f"http://127.0.0.1:{server.server_port}"
        try:
            options = {"temperature": 0.2, "top_p": 0.9, "num_predict": 16}
            sample = {"prompt": "Check the local transport", "stream": False, "options": options}
            models = ("lab-a", "lab-b", "lab-c")
            replies = [post(address, "/api/generate", dict(sample, model=model))["response"] for model in models]
            expect("industry_generate_switch", list(models), "Send three actual loopback POSTs and check the returned model fixture",
                   [["lab-a fixed reply", "lab-b fixed reply", "lab-c fixed reply"], [False] * 3, [options] * 3],
                   [replies, [payload["stream"] for _, payload in request_log],
                    [payload["options"] for _, payload in request_log]])
            history = []
            for index in range(1, 8):
                user = {"role": "user", "content": str(index)}
                payload = {"model": "lab-a", "messages": [*history, user], "stream": False}
                message = post(address, "/api/chat", payload)["message"]
                history = [*history, user, message][-10:]
            last_path, last = request_log[-1]
            expect("industry_chat_window", "seven user turns", "Retain five prior pairs and send current role separately",
                   ["/api/chat", 11, ["user", "assistant"], "2", "turn 7", 10],
                   [last_path, len(last["messages"]), [m["role"] for m in last["messages"][:2]],
                    last["messages"][0]["content"], history[-1]["content"], len(history)])
            try:
                post(address, "/api/generate", dict(sample, model="unavailable"))
            except HTTPError as exc:
                observed = [exc.code, json.loads(exc.read())["error"]]
            else:
                observed = None
            expect("industry_api_error", "unavailable", "Read a real non-2xx response as an error, not generated content",
                   [404, "local model fixture unavailable"], observed)
        finally:
            server.shutdown()
            worker.join(timeout=3)


if __name__ == "__main__":
    run_exercise(exercise)
本例需在 Python 3.12.14;环回 HTTP 样本、十进制计算,独立 Ollama 0.40.15 CPU 服务。 中运行,请复制源码、保存文件或下载工程包后在本地执行验证。
运行说明与环境独立工程

运行环境:Python 3.12.14;环回 HTTP 样本、十进制计算,独立 Ollama 0.40.15 CPU 服务。

入口文件:projects/ai-industry/industry_lab.py

本地运行步骤快速上手
  1. 点击上方“保存源码”保存为 industry_lab.py,或下载右侧课程工程包。
  2. 确认本地已准备 Python 3.12.14;环回 HTTP 样本、十进制计算,独立 Ollama 0.40.15 CPU 服务。。
  3. 按对应章节命令执行,结合正文核对实际输出。
附件与关联工程包下载

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

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

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

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

搜索教程、工具与资讯

热门搜索

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

欢迎登录蓝色天空网

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