nanobanana.py 17 KB

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