怎么给LLM传递图片,通过图片转换base64位编码处理,函数参考
 
   
# -*- coding: utf-8 -*-
"""LLM 图片"""

import base64
import mimetypes
from pathlib import Path
from typing import Any


def detect_image_mime(data: bytes) -> str | None:
"""Detect image MIME type from magic bytes, ignoring file extension."""
if data[:8] == b"\x89PNG\r\n\x1a\n":
return "image/png"
if data[:3] == b"\xff\xd8\xff":
return "image/jpeg"
if data[:6] in (b"GIF87a", b"GIF89a"):
return "image/gif"
if data[:4] == b"RIFF" and data[8:12] == b"WEBP":
return "image/webp"
return None


def read_img(
media: list[str] | None, text: str = "这是图片"
) -> str | list[dict[str, Any]]:
"""Build user message content with optional base64-encoded images."""
if not media:
return text

images = []
for path in media:
p = Path(path)
if not p.is_file():
continue
raw = p.read_bytes()
# Detect real MIME type from magic bytes; fallback to filename guess
mime = detect_image_mime(raw) or mimetypes.guess_type(path)[0]
if not mime or not mime.startswith("image/"):
continue
b64 = base64.b64encode(raw).decode()
images.append(
{"type": "image_url", "image_url": {"url": f"data:{mime};base64,{b64}"}}
)

if not images:
return text
return images + [{"type": "text", "text": text}]


if __name__ == "__main__":
media = ["../tupian.jpg"]
print(read_img(media))
   

转www.载for网站制作学习asp必.cn究