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

核对本机命令怎样组装图片和提示词

PYTHONWindows、Python 3.12.14、codex-cli 0.167.0-alpha.4.1。cli_details_lab.py
cli_details_lab.py109 行
"""Inspect CLI input assembly and exercise image arguments without making a model request."""
from base64 import b64decode
from hashlib import sha256
import json
import os
from pathlib import Path
import shutil
from struct import pack, unpack
import subprocess
import sys
from tempfile import TemporaryDirectory
import tomllib
from zlib import compress, crc32


def png(width, height, rgb):
    def chunk(kind, data):
        return pack("!I", len(data)) + kind + data + pack("!I", crc32(kind + data))

    pixels = (b"\0" + bytes(rgb) * width) * height
    header = pack("!2I5B", width, height, 8, 2, 0, 0, 0)
    return (bytes.fromhex("89504e470d0a1a0a") + chunk(b"IHDR", header)
            + chunk(b"IDAT", compress(pixels)) + chunk(b"IEND", b""))


def main():
    binary = shutil.which("codex.exe") or shutil.which("codex")
    if not binary:
        raise SystemExit("Install Codex CLI and make it available on PATH.")
    cases = []

    def check(name, data, operation, expected, actual):
        assert expected == actual, (name, expected, actual)
        cases.append(dict(name="cli_" + name, input=data, operation=operation, expected=expected, actual=actual))

    with TemporaryDirectory(prefix="mbsky-codex-prompt-") as temporary:
        root = Path(temporary)
        config = root / "codex-home"
        config.mkdir()
        env = dict(os.environ, CODEX_HOME=str(config))

        def invoke(args):
            return subprocess.run([binary, *args], cwd=root, env=env, capture_output=True,
                                  encoding="utf-8", errors="replace", timeout=20)

        def last_input(args):
            result = invoke(["debug", "prompt-input", *args, "--", "Read the panel layout."])
            assert result.returncode == 0, result.stderr
            return json.loads(result.stdout)[-1]["content"]

        images = {"card.png": (400, 250, (30, 60, 210)), "panel.png": (320, 180, (30, 190, 40))}
        inputs = {}
        for name, (width, height, rgb) in images.items():
            blob = png(width, height, rgb)
            (root / name).write_bytes(blob)
            inputs[name] = dict(size=[width, height], rgb=rgb, sha256=sha256(blob).hexdigest())

        for name, args, dims in (
            ("single", ["-i", "card.png"], [[400, 250]]),
            ("multiple", ["-i", "card.png", "-i", "panel.png"], [[400, 250], [320, 180]]),
        ):
            content = last_input(args)
            actual = []
            for element in content:
                if element["type"] == "input_image":
                    prefix, data = element["image_url"].split(",", 1)
                    assert prefix == "data:image/png;base64"
                    actual.append(list(unpack("!2I", b64decode(data)[16:24])))
            check(name, dict(args=args, files={key: inputs[key] for key in args if key in inputs}),
                  "Decode the images in the locally rendered input and read PNG sizes", dims, actual)
            assert content[-1]["text"] == "Read the panel layout."

        args = ["--image", "missing.png"]
        content = last_input(args)
        message = any("Codex could not read the local image" in item.get("text", "")
                      and "missing.png" in item["text"] for item in content)
        check("missing", args, "Verify explicit missing-file feedback and the absence of an image",
              [True, 0], [message, sum(item["type"] == "input_image" for item in content)])

        for key, args in (("old_exec", ["exec", "--full-auto", "--help"]),
                          ("old_approval", ["--approval-mode", "full-auto", "completion", "powershell"])):
            result = invoke(args)
            check(key, args, "Read the installed parser's response to a historical option",
                  [2, True], [result.returncode, "unexpected argument" in result.stderr])

        args = ["--no-alt-screen", "completion", "powershell"]
        result = invoke(args)
        check("screen_flag", args, "Parse the display switch without opening the TUI",
              [0, True], [result.returncode, "Register-ArgumentCompleter" in result.stdout])

        args = ["exec", "--help"]
        help_text = invoke(args)
        flags = ["--model", "--output-last-message", "--ephemeral", "--json"]
        check("exec_help", dict(args=args, flags=flags), "Read exec help",
              [0, True], [help_text.returncode, all(flag in help_text.stdout for flag in flags)])

        raw = '[tui]\nalternate_screen = "never"\n'
        check("tui_config", raw, "Read the display setting in an independent TOML sample",
              "never", tomllib.loads(raw)["tui"]["alternate_screen"])
        version = invoke(["--version"])
        assert version.returncode == 0 and version.stdout.startswith("codex-cli ")

    print(json.dumps(dict(version={"python":sys.version.split()[0],"codex":version.stdout.strip()},
                          codex_sha256=sha256(Path(binary).read_bytes()).hexdigest(), cases=cases)))


if __name__ == "__main__":
    main()
本例需在 Windows、Python 3.12.14、codex-cli 0.167.0-alpha.4.1。 中运行,请复制源码、保存文件或下载工程包后在本地执行验证。
运行说明与环境独立工程

运行环境:Windows、Python 3.12.14、codex-cli 0.167.0-alpha.4.1。

入口文件:projects/codex-cli_details/cli_details_lab.py

本地运行步骤快速上手
  1. 点击上方“保存源码”保存为 cli_details_lab.py,或下载右侧课程工程包。
  2. 确认本地已准备 Windows、Python 3.12.14、codex-cli 0.167.0-alpha.4.1。。
  3. 按对应章节命令执行,结合正文核对实际输出。
附件与关联工程包下载

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

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

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

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

搜索教程、工具与资讯

热门搜索

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

欢迎登录蓝色天空网

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