Chuyển tới nội dung chính

Xây dựng Plugin nhà cung cấp tạo hình ảnh

Các plugin của nhà cung cấp gen hình ảnh đăng ký một chương trình phụ trợ phục vụ mọi lệnh gọi công cụ image_generate — DALL·E, GPT-image, Grok, Flux, Imagen, Stable Diffusion, fal, Replica, giàn ComfyUI cục bộ, bất kỳ thứ gì. Các nhà cung cấp tích hợp (OpenAI, OpenAI-Codex, xAI) đều được cung cấp dưới dạng plugin. Bạn có thể thêm một cái mới hoặc ghi đè một cái được đóng gói bằng cách thả một thư mục vào `plugins/image_gen/<name/

.

mẹo

Image-gen là một trong số plugin phụ trợ được Hermes hỗ trợ. Những loại khác (với các ABC chuyên dụng hơn) là Memory Provider Plugins, Context Engine PluginsModel Provider Plugins. Các plugin công cụ/hook/CLI chung có trong Build a Hermes Plugin.

Cách hoạt động của tính năng khám phá

Hermes quét các phần phụ trợ của gen hình ảnh ở ba nơi:

  1. Đi kèm

<repo/plugins/image_gen/<name/ (được tải tự động với kind: backend

, luôn có sẵn) 2. Người dùng

~/.Hermes/plugins/image_gen/<name/ (chọn tham gia qua plugins.enabled

) 3. pip — các gói khai báo điểm vào Hermes_agent.plugins ``Hàm register(ctx) của mỗi plugin gọi ctx.register_image_gen_provider(...) — đưa nó vào sổ đăng ký trong agent/image_gen_registry.py

. Nhà cung cấp đang hoạt động được image_gen.provider chọn trong `config.yaml

; Hermes tools hướng dẫn người dùng lựa chọn.

Trình bao bọc công cụ image_generate yêu cầu cơ quan đăng ký tìm nhà cung cấp đang hoạt động và gửi đến đó. Nếu không có nhà cung cấp nào được đăng ký, công cụ sẽ hiển thị một lỗi hữu ích khi trỏ vào `Hermes tools

.

Cấu trúc thư mục

` plugins/image_gen/my-backend/ ├── init.py # ImageGenProvider subclass + register() └── plugin.YAML # Manifest with kind: backend

` ``Một plugin đi kèm đã hoàn tất vào thời điểm này. Các plugin người dùng tại

~/.Hermes/plugins/image_gen/<name/ cần được thêm vào plugins.enabled trong config.yaml (hoặc chạy Hermes plugins enable <name

).

Nhà cung cấp ImageGen ABC

Phân lớp `agent.image_gen_provider.ImageGenProvider

. Các thành viên bắt buộc duy nhất là thuộc tính name và phương thức `generate()

  • mọi thứ khác đều có giá trị mặc định hợp lý:

# plugins/image_gen/my-backend/__init__.py
from typing import Any, Dict, List, Optional
import os`from agent.image_gen_provider import (
DEFAULT_ASPECT_RATIO,
ImageGenProvider,
error_response,
resolve_aspect_ratio,
save_b64_image,
success_response,
)

class MyBackendImageGenProvider(ImageGenProvider):
@property
def name(self) -> str:
# Stable id used in image_gen.provider config. Lowercase, no spaces.
return "my-backend"`@property
def display_name(self) -> str:
# Human label shown in
`Hermes tools

. Defaults to name.title() if omitted.
return "My Backend"`def is_available(self) -> bool:
# Return False if credentials or deps are missing.
# The tool's availability gate calls this before dispatch.
if not os.environ.get("MY_BACKEND_API_KEY"):
return False
try:
import my_backend_SDK # noqa: F401
except ImportError:
return False
return True`def list_models(self) -> List[Dict[str, Any]]:
# Catalog shown in
`Hermes tools
` model picker.
return [
&#123;
"id": "my-model-fast",
"display": "My Model (Fast)",
"speed": "~5s",
"strengths": "Quick iteration",
"price": "$0.01/image",
&#125;,
&#123;
"id": "my-model-hq",
"display": "My Model (HQ)",
"speed": "~30s",
"strengths": "Highest fidelity",
"price": "$0.04/image",
&#125;,
]

def default_model(self) -> Optional[str]:
return "my-model-fast"`def get_setup_schema(self) -> Dict[str, Any]:
# Metadata for the
`Hermes tools
` picker — keys to prompt for at setup.
return &#123;
"name": "My Backend",
"badge": "paid", # optional; shown as a short tag in the picker
"tag": "One-line description shown under the name",
"env_vars": [
&#123;
"key": "MY_BACKEND_API_KEY",
"prompt": "My Backend API key",
"url": "https://my-backend.example.com/API-keys",
&#125;,
],
&#125;`def generate(
self,
prompt: str,
aspect_ratio: str = DEFAULT_ASPECT_RATIO,
**kwargs: Any,
) -> Dict[str, Any]:
prompt = (prompt or "").strip()
aspect_ratio = resolve_aspect_ratio(aspect_ratio)

if not prompt:
return error_response(
error="Prompt is required",
error_type="invalid_input",
provider=self.name,
prompt="",
aspect_ratio=aspect_ratio,
)

# Model selection precedence: env var → config → default. The helper
# _resolve_model() in the built-in OpenAI plugin is a good reference.
model_id = kwargs.get("model") or self.default_model() or "my-model-fast"`try:
import my_backend_SDK
CLIent = my_backend_SDK.CLIent(API_key=os.environ["MY_BACKEND_API_KEY"])
result = CLIent.generate(
prompt=prompt,
model=model_id,
aspect_ratio=aspect_ratio,
)

# Two shapes supported:
# - URL string: return it as
`image

# - base64 data: save under $Hermes_HOME/cache/images/ via save_b64_image()
if result.get("image_b64"):
path = save_b64_image(
result["image_b64"],
prefix=self.name,
extension="png",
)
image = str(path)
else:
image = result["image_url"]

return success_response(
image=image,
model=model_id,
prompt=prompt,
aspect_ratio=aspect_ratio,
provider=self.name,
)
except Exception as exc:
return error_response(
error=str(exc),
error_type=type(exc).__name__,
provider=self.name,
model=model_id,
prompt=prompt,
aspect_ratio=aspect_ratio,
)

def register(ctx) -> None:
"""Plugin entry point — called once at load time."""
ctx.register_image_gen_provider(MyBackendImageGenProvider())

`

## plugin.YAML

``` yaml
name: my-backend
version: 1.0.0
description: My image backend — text-to-image via My Backend SDK
author: Your Name
kind: backend
requires_env:

- MY_BACKEND_API_KEY

`
```kind: backend
` là công cụ định tuyến plugin đến đường dẫn đăng ký gen hình ảnh.
`requires_env
` được nhắc trong
`Hermes plugins install

.

## Tài liệu tham khảo ABC

Hợp đồng đầy đủ trong
`agent/image_gen_provider.py

. Các phương pháp bạn thường ghi đè:

| Thành viên | Bắt buộc | Mặc định | Mục đích |
|---|---|---|---|
|
`name
` ||| Id ổn định được sử dụng trong cấu hình
`image_gen.provider
` |
|
`display_name
` ||

name.title()
` | Nhãn hiển thị trong
`Hermes tools
` |
|
`is_available()
` ||

True
` | Cổng thiếu tín dụng/deps |
|
`list_models()
` ||

[]
` | Danh mục dành cho bộ chọn mẫu
`Hermes tools
` |
|
`default_model()
` || đầu tiên từ
`list_models()
` | Dự phòng khi không có mô hình nào được định cấu hình |
|
`get_setup_schema()
` || tối thiểu | Siêu dữ liệu của bộ chọn + lời nhắc env-var |
|
`generate(prompt, aspect_ratio, **kwargs)
` ||| Cuộc gọi |

## Định dạng phản hồi``generate()
` phải trả về một lệnh được tạo thông qua
`success_response()
` hoặc
`error_response()

. Cả hai đều sống trong
`agent/image_gen_provider.py

.

**Thành công:**

`
``` python
success_response(
image=&lt;url-or-absolute-path>,
model=&lt;model-id>,
prompt=&lt;echoed-prompt>,
aspect_ratio="landscape" | "square" | "portrait",
provider=&lt;your-provider-name>,
extra=\{...}, # optional backend-specific fields
)

`
``**Lỗi:**

`
`Python
error_response(
error="human-readable message",
error_type="provider_error" | "invalid_input" | "&lt;exception class name>",
provider=&lt;your-provider-name>,
model=&lt;model-id>,
prompt=&lt;prompt>,
aspect_ratio=&lt;resolved aspect>,
)

`
``Trình bao bọc công cụ JSON tuần tự hóa lệnh và chuyển nó cho LLM. Lỗi được hiển thị dưới dạng kết quả của công cụ; LLM quyết định cách giải thích chúng cho người dùng.

## Xử lý đầu ra base64 và URL

Một số chương trình phụ trợ trả về URL hình ảnh (fal, Replica); những người khác trả về tải trọng base64 (OpenAI GPT-image-2). Đối với trường hợp base64, hãy sử dụng
`save_b64_image()

- nó ghi vào

$Hermes_HOME/cache/images/&lt;prefix>_&lt;timestamp>_&lt;uuid>.&lt;ext>
` và trả về
`Path
` tuyệt đối. Vượt qua đường dẫn đó (dưới dạng
`str

) dưới dạng
`image=
` trong
`success_response()

. Phân phối qua cổng (bong bóng ảnh Telegram, tệp đính kèm Discord) nhận dạng cả URL và đường dẫn tuyệt đối.

## Ghi đè của người dùng

Bỏ plugin người dùng tại

~/.Hermes/plugins/image_gen/&lt;name>/
` với cùng thuộc tính
`name
` dưới dạng gói và kích hoạt nó thông qua
`Hermes plugins enable &lt;name>

- sổ đăng ký là người viết cuối cùng thắng, vì vậy phiên bản của bạn sẽ thay thế phiên bản tích hợp sẵn. Hữu ích khi trỏ plugin
`OpenAI
` vào proxy riêng hoặc trao đổi trong danh mục mô hình tùy chỉnh.`##Thử nghiệm

`bash
export Hermes_HOME=/tmp/Hermes-imggen-test
mkdir -p $Hermes_HOME/plugins/image_gen/my-backend

# …copy __init__.py + plugin.YAML into that dir…`export MY_BACKEND_API_KEY=your-test-key
Hermes plugins enable my-backend

# Pick it as the active provider
echo "image_gen:" >> $Hermes_HOME/config.yaml
echo " provider: my-backend" >> $Hermes_HOME/config.yaml

# Exercise it
Hermes -z "Generate an image of a corgi in a spacesuit"

`
``Hoặc tương tác:
`Hermes tools
` → "Tạo hình ảnh" → chọn
`my-backend
` → nhập khóa API nếu được nhắc.

## Triển khai tham khảo- **
`plugins/image_gen/OpenAI/__init__.py

** — GPT-image-2 ở các cấp thấp/trung bình/cao dưới dạng ba ID mô hình ảo chia sẻ một mô hình API với các thông số
`quality
` khác nhau. Ví dụ điển hình về các mô hình theo cấp bậc trong một chuỗi ưu tiên phụ trợ + config.yaml.
- **
`plugins/image_gen/xai/__init__.py

** — Grok Imagine qua xAI. Hình dạng khác nhau (đầu ra URL, danh mục đơn giản hơn).
- **
`plugins/image_gen/OpenAI-Codex/__init__.py

** — Biến thể API phản hồi kiểu Codex sử dụng lại SDK OpenAI với URL cơ sở định tuyến khác.

## Phân phối qua pip

``` toml

# pyproject.TOML
[project.entry-points."Hermes_agent.plugins"]
my-backend-imggen = "my_backend_imggen_package"

`
```my_backend_imggen_package
` phải hiển thị chức năng
`register
` cấp cao nhất. Xem [Distribute via pip](/docs/guides/build-a-Hermes-plugin#distribute-via-pip) trong hướng dẫn plugin chung để biết cách thiết lập đầy đủ.

## Các trang liên quan
- [Image Generation](/docs/user-guide/features/image-generation) — tài liệu về tính năng hướng tới người dùng
- [Plugins overview](/docs/user-guide/features/plugins) - tổng quan về tất cả các loại plugin
- [Build a Hermes Plugin](/docs/guides/build-a-Hermes-plugin) — hướng dẫn sử dụng các công cụ/móc/dấu gạch chéo chung