nanobanana.py 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487
  1. """
  2. NanoBanana Tool - 图像生成
  3. 通用图像生成工具,可以接受自然语言描述和/或图像输入,生成新的图像。
  4. 支持通过 OpenRouter 调用 Gemini 2.5 Flash Image 模型。
  5. """
  6. import base64
  7. import json
  8. import mimetypes
  9. import os
  10. import re
  11. from pathlib import Path
  12. from typing import Optional, Dict, Any, List, Tuple
  13. import httpx
  14. from dotenv import load_dotenv
  15. from agent.tools import tool, ToolResult
  16. OPENROUTER_BASE_URL = "https://openrouter.ai/api/v1"
  17. DEFAULT_TIMEOUT = 120.0
  18. DEFAULT_IMAGE_PROMPT = "根据输入生成图像。"
  19. DEFAULT_IMAGE_MODEL_CANDIDATES = [
  20. # "google/gemini-2.5-flash-image",
  21. "google/gemini-3.1-flash-image-preview"
  22. ]
  23. def _resolve_api_key() -> Optional[str]:
  24. """优先读取环境变量,缺失时尝试从 .env 加载。"""
  25. api_key = os.getenv("OPENROUTER_API_KEY") or os.getenv("OPEN_ROUTER_API_KEY")
  26. if api_key:
  27. return api_key
  28. load_dotenv()
  29. return os.getenv("OPENROUTER_API_KEY") or os.getenv("OPEN_ROUTER_API_KEY")
  30. def _image_to_data_url(image_path: Path) -> str:
  31. """将图片文件编码为 data URL。"""
  32. mime_type = mimetypes.guess_type(str(image_path))[0] or "application/octet-stream"
  33. raw = image_path.read_bytes()
  34. b64 = base64.b64encode(raw).decode("utf-8")
  35. return f"data:{mime_type};base64,{b64}"
  36. def _safe_json_parse(content: str) -> Dict[str, Any]:
  37. """尽量从模型文本中提取 JSON。"""
  38. try:
  39. return json.loads(content)
  40. except json.JSONDecodeError:
  41. start = content.find("{")
  42. end = content.rfind("}")
  43. if start != -1 and end != -1 and end > start:
  44. candidate = content[start:end + 1]
  45. return json.loads(candidate)
  46. raise
  47. def _extract_data_url_images(message: Dict[str, Any]) -> List[Tuple[str, str]]:
  48. """
  49. 从 OpenRouter 响应消息中提取 data URL 图片。
  50. Returns:
  51. List[(mime_type, base64_data)]
  52. """
  53. extracted: List[Tuple[str, str]] = []
  54. # 官方文档中的主要位置:message.images[]
  55. for img in message.get("images", []) or []:
  56. if not isinstance(img, dict):
  57. continue
  58. if img.get("type") != "image_url":
  59. continue
  60. data_url = ((img.get("image_url") or {}).get("url") or "").strip()
  61. if not data_url.startswith("data:"):
  62. continue
  63. m = re.match(r"^data:([^;]+);base64,(.+)$", data_url, flags=re.DOTALL)
  64. if not m:
  65. continue
  66. extracted.append((m.group(1), m.group(2)))
  67. # 兼容某些模型可能把 image_url 放在 content 数组中
  68. content = message.get("content")
  69. if isinstance(content, list):
  70. for part in content:
  71. if not isinstance(part, dict):
  72. continue
  73. if part.get("type") != "image_url":
  74. continue
  75. data_url = ((part.get("image_url") or {}).get("url") or "").strip()
  76. if not data_url.startswith("data:"):
  77. continue
  78. m = re.match(r"^data:([^;]+);base64,(.+)$", data_url, flags=re.DOTALL)
  79. if not m:
  80. continue
  81. extracted.append((m.group(1), m.group(2)))
  82. return extracted
  83. def _extract_image_refs(choice: Dict[str, Any], message: Dict[str, Any]) -> List[Dict[str, str]]:
  84. """
  85. 尝试从不同响应格式中提取图片引用。
  86. 返回格式:
  87. - {"kind": "data_url", "value": "data:image/png;base64,..."}
  88. - {"kind": "base64", "value": "...", "mime_type": "image/png"}
  89. - {"kind": "url", "value": "https://..."}
  90. """
  91. refs: List[Dict[str, str]] = []
  92. # 1) 标准 message.images
  93. for img in message.get("images", []) or []:
  94. if not isinstance(img, dict):
  95. continue
  96. # image_url 结构
  97. data_url = ((img.get("image_url") or {}).get("url") or "").strip()
  98. if data_url.startswith("data:"):
  99. refs.append({"kind": "data_url", "value": data_url})
  100. continue
  101. if data_url.startswith("http"):
  102. refs.append({"kind": "url", "value": data_url})
  103. continue
  104. # 兼容 base64 字段
  105. b64 = (img.get("b64_json") or img.get("base64") or "").strip()
  106. if b64:
  107. refs.append({"kind": "base64", "value": b64, "mime_type": img.get("mime_type", "image/png")})
  108. # 2) 某些格式可能在 choice.images
  109. for img in choice.get("images", []) or []:
  110. if not isinstance(img, dict):
  111. continue
  112. data_url = ((img.get("image_url") or {}).get("url") or "").strip()
  113. if data_url.startswith("data:"):
  114. refs.append({"kind": "data_url", "value": data_url})
  115. continue
  116. if data_url.startswith("http"):
  117. refs.append({"kind": "url", "value": data_url})
  118. continue
  119. b64 = (img.get("b64_json") or img.get("base64") or "").strip()
  120. if b64:
  121. refs.append({"kind": "base64", "value": b64, "mime_type": img.get("mime_type", "image/png")})
  122. # 3) content 数组里的 image_url
  123. content = message.get("content")
  124. if isinstance(content, list):
  125. for part in content:
  126. if not isinstance(part, dict):
  127. continue
  128. if part.get("type") != "image_url":
  129. continue
  130. url = ((part.get("image_url") or {}).get("url") or "").strip()
  131. if url.startswith("data:"):
  132. refs.append({"kind": "data_url", "value": url})
  133. elif url.startswith("http"):
  134. refs.append({"kind": "url", "value": url})
  135. # 4) 极端兼容:文本中可能出现 data:image 或 http 图片 URL
  136. if isinstance(content, str):
  137. # data URL
  138. for m in re.finditer(r"(data:image\/[a-zA-Z0-9.+-]+;base64,[A-Za-z0-9+/=]+)", content):
  139. refs.append({"kind": "data_url", "value": m.group(1)})
  140. # http(s) 图片链接
  141. for m in re.finditer(r"(https?://\S+\.(?:png|jpg|jpeg|webp))", content, flags=re.IGNORECASE):
  142. refs.append({"kind": "url", "value": m.group(1)})
  143. return refs
  144. def _mime_to_ext(mime_type: str) -> str:
  145. """MIME 类型映射到扩展名。"""
  146. mapping = {
  147. "image/png": ".png",
  148. "image/jpeg": ".jpg",
  149. "image/webp": ".webp",
  150. }
  151. return mapping.get(mime_type.lower(), ".png")
  152. def _normalize_model_id(model_id: str) -> str:
  153. """
  154. 规范化常见误写模型 ID,减少无效重试。
  155. """
  156. if not model_id:
  157. return model_id
  158. m = model_id.strip()
  159. # 常见误写:gemini/gemini-xxx -> google/gemini-xxx
  160. if m.startswith("gemini/"):
  161. m = "google/" + m.split("/", 1)[1]
  162. # 常见顺序误写:preview-image -> image
  163. if "gemini-2.5-flash-preview-image" in m:
  164. m = m.replace("gemini-2.5-flash-preview-image", "gemini-2.5-flash-image")
  165. # 兼容旧 ID 到当前可用 ID
  166. if "gemini-2.5-flash-image-preview" in m:
  167. m = m.replace("gemini-2.5-flash-image-preview", "gemini-2.5-flash-image")
  168. return m
  169. @tool(description="通用的图像生成工具,根据文本描述和/或参考图像生成图片。输出格式只有图片,不能输出文字。")
  170. async def nanobanana(
  171. image_path: str = "",
  172. image_paths: Optional[List[str]] = None,
  173. prompt: Optional[str] = None,
  174. model: Optional[str] = None,
  175. max_tokens: int = 1200,
  176. image_output_path: Optional[str] = None,
  177. ) -> ToolResult:
  178. """
  179. 通用图像生成工具,可以接受自然语言描述和/或图像输入,生成新的图像。
  180. Args:
  181. image_path: 输入图片路径(单图模式,可选)
  182. image_paths: 输入图片路径列表(多图模式,可选)
  183. prompt: 自定义生成描述(可选,默认使用通用prompt)
  184. model: OpenRouter 模型名(可选,默认使用 gemini-2.5-flash-image)
  185. max_tokens: 最大输出 token
  186. image_output_path: 生成图片保存路径(可选)
  187. Returns:
  188. ToolResult: 包含生成的图片路径
  189. """
  190. raw_paths: List[str] = []
  191. if image_paths:
  192. raw_paths.extend(image_paths)
  193. if image_path:
  194. raw_paths.append(image_path)
  195. # 图像输入是可选的,但如果提供了就需要验证
  196. input_paths: List[Path] = []
  197. if raw_paths:
  198. # 去重并检查路径
  199. unique_raw: List[str] = []
  200. seen = set()
  201. for p in raw_paths:
  202. if p and p not in seen:
  203. unique_raw.append(p)
  204. seen.add(p)
  205. input_paths = [Path(p) for p in unique_raw]
  206. invalid = [str(p) for p in input_paths if (not p.exists() or not p.is_file())]
  207. if invalid:
  208. return ToolResult(
  209. title="NanoBanana 生成失败",
  210. output="",
  211. error=f"以下图片不存在或不可读: {invalid}",
  212. )
  213. api_key = _resolve_api_key()
  214. if not api_key:
  215. return ToolResult(
  216. title="NanoBanana 生成失败",
  217. output="",
  218. error="未找到 OpenRouter API Key,请设置 OPENROUTER_API_KEY 或 OPEN_ROUTER_API_KEY",
  219. )
  220. user_prompt = prompt or DEFAULT_IMAGE_PROMPT
  221. # 编码图像(如果有)
  222. image_data_urls = []
  223. if input_paths:
  224. try:
  225. image_data_urls = [_image_to_data_url(p) for p in input_paths]
  226. except Exception as e:
  227. return ToolResult(
  228. title="NanoBanana 生成失败",
  229. output="",
  230. error=f"图片编码失败: {e}",
  231. )
  232. user_content: List[Dict[str, Any]] = [{"type": "text", "text": user_prompt}]
  233. for u in image_data_urls:
  234. user_content.append({"type": "image_url", "image_url": {"url": u}})
  235. payload: Dict[str, Any] = {
  236. "messages": [
  237. {
  238. "role": "system",
  239. "content": "你是图像生成助手。请根据用户的描述和/或输入图像生成新的图像。",
  240. },
  241. {
  242. "role": "user",
  243. "content": user_content,
  244. },
  245. ],
  246. "temperature": 0.2,
  247. "max_tokens": max_tokens,
  248. "modalities": ["image", "text"],
  249. }
  250. headers = {
  251. "Authorization": f"Bearer {api_key}",
  252. "Content-Type": "application/json",
  253. "HTTP-Referer": "https://local-agent",
  254. "X-Title": "Agent NanoBanana Tool",
  255. }
  256. endpoint = f"{OPENROUTER_BASE_URL}/chat/completions"
  257. # 自动尝试多个可用模型,减少 404/invalid model 影响
  258. candidates: List[str] = []
  259. if model:
  260. candidates.append(_normalize_model_id(model))
  261. if env_model := os.getenv("NANOBANANA_IMAGE_MODEL"):
  262. candidates.append(_normalize_model_id(env_model))
  263. candidates.extend([_normalize_model_id(x) for x in DEFAULT_IMAGE_MODEL_CANDIDATES])
  264. # 去重并保持顺序
  265. dedup: List[str] = []
  266. seen = set()
  267. for m in candidates:
  268. if m and m not in seen:
  269. dedup.append(m)
  270. seen.add(m)
  271. candidates = dedup
  272. data: Optional[Dict[str, Any]] = None
  273. used_model: Optional[str] = None
  274. errors: List[Dict[str, Any]] = []
  275. for cand in candidates:
  276. modality_attempts: List[Optional[List[str]]] = [["image", "text"], ["image"], None]
  277. for mods in modality_attempts:
  278. trial_payload = dict(payload)
  279. trial_payload["model"] = cand
  280. if mods is None:
  281. trial_payload.pop("modalities", None)
  282. else:
  283. trial_payload["modalities"] = mods
  284. try:
  285. async with httpx.AsyncClient(timeout=DEFAULT_TIMEOUT) as client:
  286. resp = await client.post(endpoint, json=trial_payload, headers=headers)
  287. resp.raise_for_status()
  288. data = resp.json()
  289. used_model = cand
  290. break
  291. except httpx.HTTPStatusError as e:
  292. errors.append({
  293. "model": cand,
  294. "modalities": mods,
  295. "status_code": e.response.status_code,
  296. "body": e.response.text[:600],
  297. })
  298. continue
  299. except Exception as e:
  300. errors.append({
  301. "model": cand,
  302. "modalities": mods,
  303. "status_code": None,
  304. "body": str(e)[:600],
  305. })
  306. continue
  307. if data is not None:
  308. break
  309. if data is None:
  310. return ToolResult(
  311. title="NanoBanana 生成失败",
  312. output=json.dumps({"attempted_models": candidates, "errors": errors}, ensure_ascii=False, indent=2),
  313. long_term_memory="All candidate models failed for this request",
  314. metadata={"attempted_models": candidates, "errors": errors},
  315. )
  316. chosen_model = used_model or candidates[0]
  317. choices = data.get("choices") or []
  318. message = choices[0].get("message", {}) if choices else {}
  319. # 提取生成的图像
  320. refs = _extract_image_refs(choices[0] if choices else {}, message)
  321. if not refs:
  322. content = message.get("content")
  323. preview = ""
  324. if isinstance(content, str):
  325. preview = content[:500]
  326. elif isinstance(content, list):
  327. preview = json.dumps(content[:3], ensure_ascii=False)[:500]
  328. return ToolResult(
  329. title="NanoBanana 生成失败",
  330. output=json.dumps(data, ensure_ascii=False, indent=2),
  331. error="模型未返回可解析图片(未在 message.images/choice.images/content 中发现图片)",
  332. metadata={
  333. "model": chosen_model,
  334. "choice_keys": list((choices[0] if choices else {}).keys()),
  335. "message_keys": list(message.keys()) if isinstance(message, dict) else [],
  336. "content_preview": preview,
  337. },
  338. )
  339. output_paths: List[str] = []
  340. if image_output_path:
  341. base_path = Path(image_output_path)
  342. else:
  343. if len(input_paths) > 1:
  344. base_path = input_paths[0].parent / "set_generated.png"
  345. else:
  346. base_path = input_paths[0].parent / f"{input_paths[0].stem}_generated.png"
  347. base_path.parent.mkdir(parents=True, exist_ok=True)
  348. for idx, ref in enumerate(refs):
  349. kind = ref.get("kind", "")
  350. mime_type = "image/png"
  351. raw_bytes: Optional[bytes] = None
  352. if kind == "data_url":
  353. m = re.match(r"^data:([^;]+);base64,(.+)$", ref.get("value", ""), flags=re.DOTALL)
  354. if not m:
  355. continue
  356. mime_type = m.group(1)
  357. raw_bytes = base64.b64decode(m.group(2))
  358. elif kind == "base64":
  359. mime_type = ref.get("mime_type", "image/png")
  360. raw_bytes = base64.b64decode(ref.get("value", ""))
  361. elif kind == "url":
  362. url = ref.get("value", "")
  363. try:
  364. with httpx.Client(timeout=DEFAULT_TIMEOUT) as client:
  365. r = client.get(url)
  366. r.raise_for_status()
  367. raw_bytes = r.content
  368. mime_type = r.headers.get("content-type", "image/png").split(";")[0]
  369. except Exception:
  370. continue
  371. else:
  372. continue
  373. if not raw_bytes:
  374. continue
  375. ext = _mime_to_ext(mime_type)
  376. if len(refs) == 1:
  377. target = base_path
  378. if target.suffix.lower() not in [".png", ".jpg", ".jpeg", ".webp"]:
  379. target = target.with_suffix(ext)
  380. else:
  381. stem = base_path.stem
  382. target = base_path.with_name(f"{stem}_{idx+1}{ext}")
  383. try:
  384. target.write_bytes(raw_bytes)
  385. output_paths.append(str(target))
  386. except Exception as e:
  387. return ToolResult(
  388. title="NanoBanana 生成失败",
  389. output="",
  390. error=f"写入生成图片失败: {e}",
  391. metadata={"model": chosen_model},
  392. )
  393. if not output_paths:
  394. return ToolResult(
  395. title="NanoBanana 生成失败",
  396. output=json.dumps(data, ensure_ascii=False, indent=2),
  397. error="检测到图片引用但写入失败(可能是无效 base64 或 URL 不可访问)",
  398. metadata={"model": chosen_model, "ref_count": len(refs)},
  399. )
  400. usage = data.get("usage", {})
  401. prompt_tokens = usage.get("prompt_tokens") or usage.get("input_tokens", 0)
  402. completion_tokens = usage.get("completion_tokens") or usage.get("output_tokens", 0)
  403. summary = {
  404. "model": chosen_model,
  405. "input_images": [str(p) for p in input_paths],
  406. "input_count": len(input_paths),
  407. "generated_images": output_paths,
  408. "prompt_tokens": prompt_tokens,
  409. "completion_tokens": completion_tokens,
  410. }
  411. return ToolResult(
  412. title="NanoBanana 图片生成完成",
  413. output=json.dumps({"summary": summary}, ensure_ascii=False, indent=2),
  414. long_term_memory=f"Generated {len(output_paths)} image(s) from {len(input_paths)} input image(s) using {chosen_model}",
  415. attachments=output_paths,
  416. metadata=summary,
  417. tool_usage={
  418. "model": chosen_model,
  419. "prompt_tokens": prompt_tokens,
  420. "completion_tokens": completion_tokens,
  421. }
  422. )