"""Local image preprocessing, verification and SDK payload exercise."""
import base64
from io import BytesIO
import json
from pathlib import Path
import sys
import httpx2 as httpx
import openai
from PIL import Image, ImageDraw, UnidentifiedImageError
from lab_tools import run_exercise
PREFIX="data:image/jpeg;base64,"
def make_sample(path):
image=Image.new("RGBA",(320,160),(0,0,0,0))
draw=ImageDraw.Draw(image)
draw.rectangle((30,26,140,133),fill=(24,109,151,255))
draw.rectangle((183,35,286,126),fill=(232,139,36,128))
image.save(path)
def prepare_image(path, max_side=160):
with Image.open(path) as source:
if source.mode in {"RGBA","LA"} or "transparency" in source.info:
foreground=source.convert("RGBA")
background=Image.new("RGBA",foreground.size,"white")
rgb=Image.alpha_composite(background,foreground).convert("RGB")
else:
rgb=source.convert("RGB")
rgb.thumbnail((max_side,max_side),Image.Resampling.LANCZOS)
buffer=BytesIO()
rgb.save(buffer,format="JPEG",quality=90)
return PREFIX+base64.b64encode(buffer.getvalue()).decode("ascii")
def parse_payload(url):
assert url.startswith(PREFIX)
data=base64.b64decode(url.removeprefix(PREFIX),validate=True)
assert data.startswith(b"\xff\xd8")
with Image.open(BytesIO(data)) as image:
assert image.format=="JPEG"
return image.copy()
def exercise(checks,root,figure=None):
sample=root/"station-colors.png"
make_sample(sample)
encoded=prepare_image(sample)
image=parse_payload(encoded)
expect=checks.expect
expect("multi_jpeg","320×160 RGBA; bound 160","Flatten alpha, resize and decode the JPEG data URI",
["RGB",[160,80]],[image.mode,list(image.size)])
colors=[image.getpixel(p) for p in ((5,5),(35,35),(115,35))]
targets=[(255,255,255),(24,109,151),(243,197,145)]
expect("multi_alpha","transparent, opaque and half-transparent areas","Compare decoded interior pixels with RGB blending",
[True,True,True],[max(abs(x-y) for x,y in zip(a,b))<=5 for a,b in zip(colors,targets)])
if figure is not None:
image.save(figure,format="PNG")
palette=Image.new("P",(20,10),0)
palette.putpalette([20,40,60]+[0]*765)
palette_path=root/"indexed.png"
palette.save(palette_path,transparency=0)
expect("multi_palette","indexed PNG with transparent index 0","Decode the JPEG from a transparent palette input",
[255,255,255],list(parse_payload(prepare_image(palette_path)).getpixel((2,2))))
broken=root/"bad.png"
broken.write_bytes(b"not an image")
rejected=[]
for path in (root/"missing.png",broken):
try:
prepare_image(path)
except (FileNotFoundError,UnidentifiedImageError) as error:
rejected.append(type(error).__name__)
expect("multi_invalid_image","missing path and corrupt file","Reject unavailable and malformed inputs",
["FileNotFoundError","UnidentifiedImageError"],rejected)
observed=[]
def handler(request):
assert request.url.host=="vision.invalid" and request.url.path=="/api/v3/chat/completions"
assert request.headers["Authorization"]=="Bearer local-fixture"
body=json.loads(request.content)
content=body["messages"][-1]["content"]
uploaded=parse_payload(content[1]["image_url"]["url"])
observed.append({"roles":[m["role"] for m in body["messages"]],
"types":[item["type"] for item in content],"prompt":content[0]["text"],
"dimensions":list(uploaded.size),"same_pixels":uploaded.tobytes()==image.tobytes(),"model":body["model"]})
return httpx.Response(200,json={"id":"vision-fixture","object":"chat.completion","created":1,
"model":body["model"],"choices":[{"index":0,"message":{"role":"assistant",
"content":"Fixture received a 160×80 JPEG."},"finish_reason":"stop"}]})
with openai.OpenAI(api_key="local-fixture",base_url="https://vision.invalid/api/v3",max_retries=0,
http_client=httpx.Client(transport=httpx.MockTransport(handler),trust_env=False)) as api:
content=[{"type":"text","text":"Describe the supplied sample."},
{"type":"image_url","image_url":{"url":encoded}}]
messages=[{"role":"user","content":content}]
first=api.chat.completions.create(model="vision-fixture",messages=messages).choices[0].message.content
messages.extend(({"role":"assistant","content":first},{"role":"user","content":content}))
second=api.chat.completions.create(model="vision-fixture",messages=messages).choices[0].message.content
expect("multi_payload","local file and prompt","Inspect real SDK request bytes through a fixture transport",
{"roles":["user"],"types":["text","image_url"],"prompt":"Describe the supplied sample.",
"dimensions":[160,80],"same_pixels":True,"model":"vision-fixture"},observed[0])
expect("multi_history","append actual prior reply and another user turn","Inspect second request roles and response",
[["user","assistant","user"],"Fixture received a 160×80 JPEG."],[observed[1]["roles"],second])
expect("multi_runtime","installed exercise dependencies","Read exact runtime versions",
["13.0.0","3.46.0"],[Image.__version__,openai.__version__])
if __name__=="__main__":
if len(sys.argv)==1:
run_exercise(exercise)
elif len(sys.argv)==3 and sys.argv[1]=="--figure-output":
run_exercise(lambda checks,root: exercise(checks,root,Path(sys.argv[2])))
else:
raise SystemExit("usage: multimodal.py [--figure-output PNG]")
本例需在 CPython 3.12,OpenAI SDK 3.46.0,httpx2 2.16.0;图片练习另用 Pillow 13.0.0 中运行,请复制源码、保存文件或下载工程包后在本地执行验证。
运行说明与环境独立工程
运行环境:CPython 3.12,OpenAI SDK 3.46.0,httpx2 2.16.0;图片练习另用 Pillow 13.0.0
入口文件:projects/ai-agent-llm-modal/multimodal.py
本地运行步骤快速上手
- 点击上方“保存源码”保存为
multimodal.py,或下载右侧课程工程包。 - 确认本地已准备 CPython 3.12,OpenAI SDK 3.46.0,httpx2 2.16.0;图片练习另用 Pillow 13.0.0。
- 按对应章节命令执行,结合正文核对实际输出。
附件与关联工程包下载
课程关联工程包(登记关联48章) · 含当前章节或实例 · mbskycom202612a3073.zip
课程关联工程包(登记关联2章) · 含当前章节或实例 · mbskycom202612a3089.zip