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

检查提供方配置和本机协议响应

PYTHONCPython 3.12,本机回环 HTTP,Edge 与 Apache ECharts 6.1.0。provider_lab.py
provider_lab.py108 行
"""Validate a training provider profile and exercise a loopback Responses fixture."""
from http.server import BaseHTTPRequestHandler, HTTPServer
from threading import Thread
import json
import sys
import tomllib
from urllib.error import HTTPError
from urllib.request import ProxyHandler, Request, build_opener


PROFILE = """
model = "deepseek-flash"
model_provider = "deepseek"
model_reasoning_effort = "high"
model_catalog_json = "models.json"

[model_providers.deepseek]
name = "DeepSeek"
base_url = "https://api.deepseek.com/"
wire_api = "responses"
env_key = "DEEPSEEK_API_KEY"
"""
MODELS = {"models": [
    {"slug": "deepseek-flash", "input_modalities": ["text", "image"]},
    {"slug": "deepseek-v4-pro", "input_modalities": ["text"]},
]}
TOKEN = "local-fixture-value"


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

    def do_POST(self):
        body = json.loads(self.rfile.read(int(self.headers["Content-Length"])))
        if self.path != "/responses":
            code, result = 404, {"error": "wrong path"}
        elif self.headers.get("Authorization") != "Bearer " + TOKEN:
            code, result = 401, {"error": "authentication required"}
        elif body.get("model") not in {row["slug"] for row in MODELS["models"]} or not body.get("input"):
            code, result = 400, {"error": "unsupported model or missing input"}
        else:
            code, result = 200, {"object": "response", "status": "completed",
                                 "model": body["model"], "output": [{"type": "message",
                                 "content": [{"type": "output_text", "text": "fixture response"}]}]}
        payload = json.dumps(result).encode()
        self.send_response(code)
        self.send_header("Content-Type", "application/json")
        self.send_header("Content-Length", str(len(payload)))
        self.end_headers()
        self.wfile.write(payload)


def exercise():
    profile = tomllib.loads(PROFILE)
    model_map = {m["slug"]: m for m in json.loads(json.dumps(MODELS))["models"]}
    provider = profile["model_providers"][profile["model_provider"]]
    actual = [profile["model"], provider["wire_api"], provider["env_key"],
              model_map[profile["model"]]["input_modalities"]]
    expected = ["deepseek-flash", "responses", "DEEPSEEK_API_KEY", ["text", "image"]]
    assert actual == expected
    cases = [dict(name="deepseek_profile_parse", input="training TOML and abbreviated JSON",
                  operation="Parse profile and match its model and provider keys",
                  expected=expected, actual=actual)]
    duplicate = 'model = "another-model"\n' + PROFILE
    try:
        tomllib.loads(duplicate)
    except tomllib.TOMLDecodeError:
        rejected = True
    else:
        rejected = False
    assert rejected
    cases.append(dict(name="deepseek_duplicate_key", input="two root model keys",
                      operation="Parse invalid TOML", expected=True, actual=rejected))

    with HTTPServer(("127.0.0.1", 0), ResponsesFixture) as server:
        worker = Thread(target=server.serve_forever)
        worker.start()
        try:
            opener = build_opener(ProxyHandler({}))
            endpoint = f"http://127.0.0.1:{server.server_port}/responses"
            for case, token, model, expected in (
                ("loopback_accepted", TOKEN, "deepseek-flash", [200, "fixture response"]),
                ("loopback_bad_token", "wrong-fixture-value", "deepseek-flash", [401, "authentication required"]),
                ("loopback_bad_model", TOKEN, "unknown-model", [400, "unsupported model or missing input"]),
            ):
                request = Request(endpoint, data=json.dumps({"model": model, "input": "fixture prompt"}).encode(),
                                  headers={"Content-Type": "application/json", "Authorization": f"Bearer {token}"})
                try:
                    with opener.open(request, timeout=4) as response:
                        content = json.load(response)
                        actual = [response.status, content["output"][0]["content"][0]["text"]]
                except HTTPError as response:
                    with response:
                        actual = [response.code, json.load(response)["error"]]
                assert actual == expected
                cases.append(dict(name=case, input={"model": model, "fixture_token_matches": token == TOKEN},
                                  operation="POST a JSON Responses request to 127.0.0.1",
                                  expected=expected, actual=actual))
        finally:
            server.shutdown()
            worker.join()
    return {"version": sys.version.split()[0], "cases": cases}


if __name__ == "__main__":
    print(json.dumps(exercise()))
本例需在 CPython 3.12,本机回环 HTTP,Edge 与 Apache ECharts 6.1.0。 中运行,请复制源码、保存文件或下载工程包后在本地执行验证。
运行说明与环境独立工程

运行环境:CPython 3.12,本机回环 HTTP,Edge 与 Apache ECharts 6.1.0。

入口文件:projects/codex-deepseek/provider_lab.py

本地运行步骤快速上手
  1. 点击上方“保存源码”保存为 provider_lab.py,或下载右侧课程工程包。
  2. 确认本地已准备 CPython 3.12,本机回环 HTTP,Edge 与 Apache ECharts 6.1.0。。
  3. 按对应章节命令执行,结合正文核对实际输出。
附件与关联工程包下载

下载课程关联工程包:Codex 教程

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

下载课程关联工程包:Codex 教程

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

搜索教程、工具与资讯

热门搜索

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

欢迎登录蓝色天空网

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