更新於 2025年9月11日
6 分鐘
您將獲得:使用 Gemini 2.5 Flash Image 模型的實用、端到端工作流程,包括提示範例、評估技巧和生產強化。
import base64import requestsAPI_KEY = "<YOUR_API_KEY>"MODEL = "gemini-2.5-flash-image" # or the provider’s exact model nameENDPOINT = "(MODEL)# Load an image into base64with open("./sample.jpg", "rb") as f: image_b64 = base64.b64encode(f.read).decode("utf-8")payload = { "contents": [{ "role": "user", "parts": [ {"text": "Describe this image in one sentence, then list three key details."}, { "inline_data": { "mime_type": "image/jpeg", "data": image_b64 } } ] }], "generationConfig": { "temperature": 0.4, "maxOutputTokens": 300 }}resp = requests.post(f"{ENDPOINT}?key={API_KEY}", json=payload)resp.raise_for_statusprint(resp.json["candidates"][0]["content"]["parts"][0]["text"]) caption、objects[]、text_blocks[] 的 JSON。」{ "caption": "<one-sentence summary>", "objects": [ {"label": "banana", "count": 2}, {"label": "bowl", "count": 1} ], "text_blocks": [ {"text": "NANO BANANA", "bbox": [x,y,w,h]} ]}payload = { "contents": [{ "role": "user", "parts": [ {"text": "Add a subtle label 'Sample' in the top-right corner."}, {"inline_data": {"mime_type": "image/png", "data": image_b64}} ] }], "generationConfig": {"temperature": 0.3, "maxOutputTokens": 0}, "tools": [{"imageEdit": {"strength": 0.25}}]}strength 較低以進行最小的編輯。null」maxOutputTokens 以獲得確定性輸出temperature (0.1–0.4)objects、dominant_color、styleconfidence: low。」from fastapi import FastAPI, UploadFile, Fileimport base64, requests, osapp = FastAPIAPI_KEY = os.getenv("API_KEY")MODEL = "gemini-2.5-flash-image"ENDPOINT = f"("/caption")async def caption(file: UploadFile = File: b = await file.read b64 = base64.b64encode(b).decode("utf-8") payload = { "contents": [{ "role": "user", "parts": [ {"text": "Return concise JSON with fields: caption, objects[]."}, {"inline_data": {"mime_type": file.content_type, "data": b64}} ] }], "generationConfig": {"temperature": 0.2, "maxOutputTokens": 200} } r = requests.post(f"{ENDPOINT}?key={API_KEY}", json=payload, timeout=30) r.raise_for_status return r.jsonstrict_json 後處理器,或要求使用圍欄 JSON ```json 區塊unsure」