Documentation
¶
Overview ¶
Package sdk is a Go client for the Comfy API v2: Comfy Cloud, or any deployment that speaks the same contract, such as comfy-api-proxy in front of a self-hosted ComfyUI. Code written against it runs unchanged on either; only the base URL and key differ.
It is a port of the Python comfy-sdk's v2 surface: local blake3 dedup uploads, core/ASSET substitution, idempotent submit with Retry-After backoff, polling with an adaptive schedule, a live SSE event stream backed by polling, range-aware downloads, and typed errors.
client, err := sdk.New(sdk.WithBaseURL("http://127.0.0.1:8189")) // or COMFY_BASE_URL
wf, err := sdk.WorkflowFromFile("workflow_api.json")
wf.SetInput("10", "image", client.AssetFromFile("photo.png"))
job, err := client.Run(ctx, wf, sdk.SubmitOptions{})
err = job.GetOutputs("9")[0].ToFile(ctx, "out.png", nil)
Targets and credentials ¶
The base URL is WithBaseURL, else COMFY_BASE_URL, else CloudBaseURL. The key is WithAPIKey, else COMFY_API_KEY. Comfy Cloud requires a key; another deployment without auth needs none. The bearer token is sent only to the base URL's origin and the Comfy Router origin.
Errors ¶
Every failure the API reports is an *APIError. Match it with errors.Is against a sentinel such as ErrNotFound, or read its fields with errors.As. A failure that produced no response is a *TransportError. A job that ends other than succeeded is a *JobFailedError from Job.Result and Client.Run.
Comfy Router ¶
Client.Models runs hosted models on Comfy Router with the same key. Model runs are billed; see Models.Run and RetryPolicy.
Concurrency ¶
A Client, Job, Asset, and Models are safe for concurrent use.
Index ¶
- Constants
- Variables
- func IsTerminal(status string) bool
- func ParseModelID(model string) (string, string, error)
- func ParseRequestID(id string) error
- func ValidateIdempotencyKey(key string) error
- type APIError
- type Asset
- func (a *Asset) Commit(ctx context.Context) (string, error)
- func (a *Asset) CreatedNew() *bool
- func (a *Asset) Delete(ctx context.Context) error
- func (a *Asset) DownloadURL(ctx context.Context) (DownloadURL, error)
- func (a *Asset) ExpiresAt() *time.Time
- func (a *Asset) FilePath() string
- func (a *Asset) Hash() (string, error)
- func (a *Asset) ID() string
- func (a *Asset) JobID() *string
- func (a *Asset) Reference(ctx context.Context) (map[string]any, error)
- type BinaryResult
- type CatalogModel
- type Client
- func (c *Client) AssetFromBytes(data []byte, filename, contentType string) *Asset
- func (c *Client) AssetFromFile(p string) *Asset
- func (c *Client) AssetFromReader(r io.Reader, filename, contentType string) (*Asset, error)
- func (c *Client) AssetFromURL(ctx context.Context, rawURL string) (*Asset, error)
- func (c *Client) Authenticated() bool
- func (c *Client) BaseURL() string
- func (c *Client) DeleteAsset(ctx context.Context, id string) error
- func (c *Client) GetAsset(ctx context.Context, id string) (*Asset, error)
- func (c *Client) GetJob(ctx context.Context, id string) (*Job, error)
- func (c *Client) ListJobs(ctx context.Context, opts ListOptions) iter.Seq2[JobSummary, error]
- func (c *Client) Run(ctx context.Context, wf *Workflow, opts SubmitOptions) (*Job, error)
- func (c *Client) String() string
- func (c *Client) Submit(ctx context.Context, wf *Workflow, opts SubmitOptions) (*Job, error)
- type DownloadURL
- type Event
- type Job
- func (j *Job) Cancel(ctx context.Context) error
- func (j *Job) CreatedAt() time.Time
- func (j *Job) Events(ctx context.Context) iter.Seq2[Event, error]
- func (j *Job) Failure() *JobError
- func (j *Job) GetOutputs(nodeID string) []*Output
- func (j *Job) ID() string
- func (j *Job) Metadata() map[string]string
- func (j *Job) Outputs() []*Output
- func (j *Job) Progress() *JobProgress
- func (j *Job) QueuePosition() *int
- func (j *Job) Refresh(ctx context.Context) error
- func (j *Job) Result(ctx context.Context) error
- func (j *Job) Status() string
- func (j *Job) String() string
- func (j *Job) Wait(ctx context.Context) error
- func (j *Job) Workflow(ctx context.Context) (JobWorkflow, error)
- type JobError
- type JobFailedError
- type JobProgress
- type JobSummary
- type JobWorkflow
- type ListModelsOptions
- type ListOptions
- type Log
- type ModelPage
- type Models
- func (m *Models) BaseURL() string
- func (m *Models) Handle(model, requestID string) (*RequestHandle, error)
- func (m *Models) List(ctx context.Context, opts ListModelsOptions) iter.Seq2[CatalogModel, error]
- func (m *Models) Page(ctx context.Context, opts ListModelsOptions) (ModelPage, error)
- func (m *Models) Retry() RetryPolicy
- func (m *Models) Run(ctx context.Context, model string, args map[string]any, opts RunOptions) (RunOutput, error)
- func (m *Models) RunDetailed(ctx context.Context, model string, args map[string]any, opts RunOptions) (RunResult, error)
- func (m *Models) Schema(ctx context.Context, model, etag string) (SchemaResult, error)
- func (m *Models) Submit(ctx context.Context, model string, args map[string]any, opts RunOptions) (*RequestHandle, error)
- func (m *Models) Subscribe(ctx context.Context, model string, args map[string]any, opts RunOptions, ...) (RunOutput, error)
- type Option
- func WithAPIKey(key string) Option
- func WithBaseURL(u string) Option
- func WithClientInfo(info string) Option
- func WithHTTPClient(c *http.Client) Option
- func WithProxyMetadata() Option
- func WithRetry(p RetryPolicy) Option
- func WithRouterBaseURL(u string) Option
- func WithTimeout(d time.Duration) Option
- type Output
- func (o *Output) Bytes(ctx context.Context, rng *Range) ([]byte, error)
- func (o *Output) ContentType() string
- func (o *Output) DownloadURL(ctx context.Context) (DownloadURL, error)
- func (o *Output) ID() string
- func (o *Output) JobID() *string
- func (o *Output) Name() string
- func (o *Output) NodeID() string
- func (o *Output) SizeBytes() int64
- func (o *Output) String() string
- func (o *Output) ToFile(ctx context.Context, path string, rng *Range) error
- func (o *Output) ToWriter(ctx context.Context, w io.Writer, rng *Range) (int64, error)
- func (o *Output) Type() string
- func (o *Output) URLExpiresAt() time.Time
- type OutputReady
- type Preview
- type Progress
- type QueueUpdate
- type Range
- type RequestHandle
- func (h *RequestHandle) Cancel(ctx context.Context) (QueueUpdate, error)
- func (h *RequestHandle) Get(ctx context.Context) (RunOutput, error)
- func (h *RequestHandle) Model() string
- func (h *RequestHandle) RequestID() string
- func (h *RequestHandle) Status(ctx context.Context) (QueueUpdate, error)
- func (h *RequestHandle) String() string
- func (h *RequestHandle) Updates(ctx context.Context) iter.Seq2[QueueUpdate, error]
- type RetryPolicy
- type RunOptions
- type RunOutput
- type RunResult
- type SchemaResult
- type StatusChange
- type SubmitOptions
- type TransportError
- type ValidationErrorDetail
- type Workflow
Examples ¶
Constants ¶
const ( // CloudBaseURL is the hosted Comfy Cloud deployment, the default target. CloudBaseURL = "https://cloud.comfy.org" // BaseURLEnv names another deployment to target. BaseURLEnv = "COMFY_BASE_URL" // APIKeyEnv is read when no key is passed. APIKeyEnv = "COMFY_API_KEY" // RouterBaseURL is Comfy Router, where client.Models sends requests. A // separate host from the v2 API: one serves jobs and assets, the other // model-id addressed runs, and neither serves the other's routes. RouterBaseURL = "https://api.comfy.org" // RouterBaseURLEnv names another Router deployment. RouterBaseURLEnv = "COMFY_ROUTER_BASE_URL" )
const ( StatusQueued = "queued" StatusRunning = "running" StatusSucceeded = "succeeded" StatusCanceling = "canceling" StatusCanceled = "canceled" StatusFailed = "failed" StatusExpired = "expired" )
Job statuses. Canceling is not terminal: cancellation lands at the next node boundary and can take seconds.
const (
// Completed is the queue status of a finished request, failed or not.
Completed = "COMPLETED"
)
Router paths, under the Router base URL.
Variables ¶
var ( ErrMissingAPIKey = errors.New("missing API key") ErrNotFound = errors.New("not found") ErrInvalidWorkflow = errors.New("invalid workflow") ErrWorkflowFormatUI = errors.New("workflow is in UI-export format") ErrMissingAsset = errors.New("missing asset") ErrHashMismatch = errors.New("hash mismatch") ErrBlobNotFound = errors.New("blob not found") ErrIdempotencyKeyReuse = errors.New("idempotency key reuse") ErrQueueFull = errors.New("queue full") ErrForbidden = errors.New("forbidden") ErrInsufficientCredits = errors.New("insufficient credits") ErrJobFailed = errors.New("job failed") ErrInvalidResponse = errors.New("invalid response") )
Sentinel errors for the failure kinds a caller branches on. Every error the API returns is an *APIError, and errors.Is matches it against these by its code, so callers write errors.Is(err, sdk.ErrNotFound).
var ( ErrRouter = errors.New("router error") ErrInvalidInput = errors.New("invalid input") ErrContentPolicyViolation = errors.New("content policy violation") ErrProviderError = errors.New("provider error") ErrProviderTimeout = errors.New("provider timeout") ErrModelNotFound = errors.New("model not found") ErrConcurrencyLimitExceeded = errors.New("concurrency limit exceeded") ErrClientDisconnected = errors.New("client disconnected") ErrInternalError = errors.New("internal error") ErrDeadlineExceeded = errors.New("deadline exceeded") ErrNotEnabled = errors.New("not enabled") ErrRateLimited = errors.New("rate limited") ErrCancelled = errors.New("cancelled") ErrQueueTimeout = errors.New("queue timeout") ErrRequestNotFound = errors.New("request not found") ErrQueueBacklogFull = errors.New("queue backlog full") // ErrCancelRefused is a 409 refusal to cancel; ErrAlreadyCompleted, the // one refusal the contract names, also matches it. ErrCancelRefused = errors.New("cancel refused") ErrAlreadyCompleted = errors.New("already completed") )
Comfy Router error buckets, one per x-comfy-error-types value in the Router contract, in its order. ErrRouter matches any of them, and any error the Router labelled with a bucket this SDK does not know yet.
var DefaultRetry = RetryPolicy{ MaxElapsed: 60 * time.Second, InitialBackoff: 500 * time.Millisecond, BackoffFactor: 2, MaxBackoff: 15 * time.Second, Jitter: true, RetryCollectable: true, CollectMaxElapsed: 20 * time.Minute, }
DefaultRetry is the policy client.Models uses unless replaced.
var ErrIdleTimeout = errors.New("response body idle too long")
ErrIdleTimeout reports a response body that sent nothing for the idle limit. It arrives wrapped in a *TransportError.
var NoRetry = RetryPolicy{InitialBackoff: 500 * time.Millisecond, BackoffFactor: 2, MaxBackoff: 15 * time.Second}
NoRetry makes every Router call exactly one attempt.
var RouterErrorTypes = []string{
"invalid_input", "content_policy_violation", "provider_error", "provider_timeout",
"insufficient_credits", "model_not_found", "unauthorized", "forbidden",
"concurrency_limit_exceeded", "client_disconnected", "internal_error", "deadline_exceeded",
"not_enabled", "service_unavailable", "rate_limited", "cancelled", "queue_timeout",
"request_not_found", "queue_backlog_full",
}
RouterErrorTypes lists the Router buckets in contract order.
Functions ¶
func IsTerminal ¶
IsTerminal reports whether a job in status will not change again.
func ParseModelID ¶
ParseModelID splits a "{provider}/{model}" id. A three-segment variant id is not addressable on the run route yet, and "." or ".." segments would walk the request path, so both are refused.
func ParseRequestID ¶
ParseRequestID checks a queued request id can address its routes.
func ValidateIdempotencyKey ¶
ValidateIdempotencyKey checks what the contract can carry: 1 to 255 printable ASCII characters, since the value rides an HTTP header.
Types ¶
type APIError ¶
type APIError struct {
// Code is the wire code, such as "not_found", or "http_<status>" when the
// server named none the SDK recognizes.
Code string
Message string
HTTPStatus int
Details map[string]any
// RequestID is the server's X-Comfy-Request-Id, cleaned to a bounded,
// printable token so it is safe to log.
RequestID string
// RetryAfter is the Retry-After header in seconds, nil when absent.
RetryAfter *int
// IdempotencyKey is the key a failed submit was sent under, so a caller
// can poll or list for the job an ambiguous failure may have created.
IdempotencyKey string
// BodyExcerpt is a cleaned, bounded slice of a body that carried no
// message, such as a proxy's HTML error page.
BodyExcerpt string
// ErrorType is a Comfy Router error bucket, when the server sent one.
ErrorType string
// Validation holds a Router validation response's entries.
Validation []ValidationErrorDetail
// ResendRefused marks a model run whose retry was refused as a key
// reuse after an earlier attempt may have claimed the key. The error
// reported is that earlier attempt's; the generation may have happened
// and been billed, so collect it rather than starting a new one.
ResendRefused bool
}
APIError is a failure the API reported, or one the SDK refused locally before sending anything. Fields the failure did not carry are zero.
Example ¶
package main
import (
"context"
"encoding/json"
"errors"
"fmt"
"io"
"log"
"net/http"
"net/http/httptest"
"sync"
"github.com/regiellis/comfy-api-proxy-go/sdk"
)
// fakeAPI is a minimal in-process Comfy API v2 deployment for the examples:
// one job, one output, single-use idempotency keys, and metadata stored as
// the client sent it.
type fakeAPI struct {
mu sync.Mutex
keys map[string]bool
metadata json.RawMessage
}
func newFakeAPI() (*fakeAPI, *httptest.Server) {
f := &fakeAPI{keys: map[string]bool{}}
mux := http.NewServeMux()
mux.HandleFunc("POST /api/v2/jobs", f.submit)
mux.HandleFunc("GET /api/v2/jobs", f.list)
mux.HandleFunc("GET /api/v2/jobs/{id}", f.get)
mux.HandleFunc("GET /api/v2/jobs/{id}/events", f.events)
mux.HandleFunc("GET /api/v2/assets/{id}/content", f.content)
return f, httptest.NewServer(mux)
}
func (f *fakeAPI) job(status string) map[string]any {
f.mu.Lock()
defer f.mu.Unlock()
return map[string]any{
"id": "job-1", "status": status, "created_at": "2026-10-27T10:00:00Z",
"metadata": f.metadata,
"outputs": []any{map[string]any{
"node_id": "9", "name": "out.png", "type": "image", "content_type": "image/png",
"size_bytes": 8, "id": "out-1",
}},
}
}
func reply(w http.ResponseWriter, status int, v any) {
w.Header().Set("Content-Type", "application/json")
w.WriteHeader(status)
if err := json.NewEncoder(w).Encode(v); err != nil {
return
}
}
func replyError(w http.ResponseWriter, status int, code, message string) {
reply(w, status, map[string]any{"error": map[string]any{"code": code, "message": message, "details": nil}})
}
func (f *fakeAPI) submit(w http.ResponseWriter, r *http.Request) {
var body struct {
Metadata json.RawMessage `json:"metadata"`
}
if err := json.NewDecoder(r.Body).Decode(&body); err != nil {
replyError(w, http.StatusBadRequest, "invalid_request", err.Error())
return
}
key := r.Header.Get("Idempotency-Key")
f.mu.Lock()
reused := f.keys[key]
f.keys[key] = true
if !reused {
f.metadata = body.Metadata
}
f.mu.Unlock()
if reused {
replyError(w, http.StatusUnprocessableEntity, "idempotency_key_reuse", "This Idempotency-Key has already been used.")
return
}
reply(w, http.StatusCreated, f.job(sdk.StatusQueued))
}
func (f *fakeAPI) list(w http.ResponseWriter, _ *http.Request) {
reply(w, http.StatusOK, map[string]any{"jobs": []any{f.job(sdk.StatusSucceeded)}})
}
func (f *fakeAPI) get(w http.ResponseWriter, r *http.Request) {
if r.PathValue("id") != "job-1" {
replyError(w, http.StatusNotFound, "not_found", "No job "+r.PathValue("id")+".")
return
}
reply(w, http.StatusOK, f.job(sdk.StatusSucceeded))
}
func (f *fakeAPI) events(w http.ResponseWriter, _ *http.Request) {
w.Header().Set("Content-Type", "text/event-stream")
frames := "event: status\ndata: {\"status\":\"running\"}\n\n" +
"event: progress\ndata: {\"value\":0.5,\"nodes_done\":1,\"nodes_total\":2}\n\n" +
"event: status\ndata: {\"status\":\"succeeded\"}\n\n"
if _, err := io.WriteString(w, frames); err != nil {
return
}
}
func (f *fakeAPI) content(w http.ResponseWriter, _ *http.Request) {
w.Header().Set("Content-Type", "image/png")
if _, err := io.WriteString(w, "PNG data"); err != nil {
return
}
}
func main() {
_, srv := newFakeAPI()
defer srv.Close()
client, err := sdk.New(sdk.WithBaseURL(srv.URL))
if err != nil {
log.Fatal(err)
}
_, err = client.GetJob(context.Background(), "no-such-job")
if errors.Is(err, sdk.ErrNotFound) {
fmt.Println("not found")
}
var apiErr *sdk.APIError
if errors.As(err, &apiErr) {
fmt.Println(apiErr.HTTPStatus, apiErr.Code, apiErr.Message)
}
}
Output: not found 404 not_found No job no-such-job.
func (*APIError) Error ¶
Error is the server's message, followed by a body excerpt when the response carried no message.
type Asset ¶
type Asset struct {
// contains filtered or unexported fields
}
Asset is an input file. It is lazy: nothing is hashed or sent until Commit, which a Submit carrying it in the graph calls. Commit first asks the server whether it already holds identical bytes (by blake3 hash) and only uploads when it does not. An Asset is safe for concurrent use.
func (*Asset) Commit ¶
Commit makes the asset exist server-side and returns its id. Idempotent: a committed asset returns at once. A retried upload reuses one Idempotency-Key per asset, so it cannot create a second copy.
func (*Asset) CreatedNew ¶
CreatedNew reports whether the commit stored new bytes (true) or matched bytes the server already had (false). Nil before commit.
func (*Asset) DownloadURL ¶
func (a *Asset) DownloadURL(ctx context.Context) (DownloadURL, error)
DownloadURL commits the asset and resolves a URL for its bytes.
func (*Asset) Hash ¶
Hash is the local blake3 hash, computed once. It is only a dedup hint; the server recomputes it from the bytes it receives.
type BinaryResult ¶
BinaryResult is a model's own bytes, for a partner that answers with the generation itself rather than JSON.
type CatalogModel ¶
type CatalogModel struct {
ID string
Provider string
Model string
// Billing holds per-model billing facts (never prices), as the server
// sent them, so a field it adds reaches the caller without a release.
Billing map[string]any
}
CatalogModel is one runnable model.
type Client ¶
type Client struct {
// Models runs hosted models on Comfy Router, sharing this client's key.
Models *Models
// contains filtered or unexported fields
}
Client talks to one Comfy API v2 deployment and to Comfy Router. It is safe for concurrent use.
func New ¶
New builds a client. The target is WithBaseURL, else COMFY_BASE_URL, else Comfy Cloud. The key is WithAPIKey, else COMFY_API_KEY; blank counts as unset at either source. Comfy Cloud always needs a key, so its absence there is ErrMissingAPIKey here rather than a 401 on the first call. Another deployment may have no auth, so there no key means send no credentials.
Example ¶
package main
import (
"encoding/json"
"fmt"
"io"
"log"
"net/http"
"net/http/httptest"
"sync"
"github.com/regiellis/comfy-api-proxy-go/sdk"
)
// fakeAPI is a minimal in-process Comfy API v2 deployment for the examples:
// one job, one output, single-use idempotency keys, and metadata stored as
// the client sent it.
type fakeAPI struct {
mu sync.Mutex
keys map[string]bool
metadata json.RawMessage
}
func newFakeAPI() (*fakeAPI, *httptest.Server) {
f := &fakeAPI{keys: map[string]bool{}}
mux := http.NewServeMux()
mux.HandleFunc("POST /api/v2/jobs", f.submit)
mux.HandleFunc("GET /api/v2/jobs", f.list)
mux.HandleFunc("GET /api/v2/jobs/{id}", f.get)
mux.HandleFunc("GET /api/v2/jobs/{id}/events", f.events)
mux.HandleFunc("GET /api/v2/assets/{id}/content", f.content)
return f, httptest.NewServer(mux)
}
func (f *fakeAPI) job(status string) map[string]any {
f.mu.Lock()
defer f.mu.Unlock()
return map[string]any{
"id": "job-1", "status": status, "created_at": "2026-10-27T10:00:00Z",
"metadata": f.metadata,
"outputs": []any{map[string]any{
"node_id": "9", "name": "out.png", "type": "image", "content_type": "image/png",
"size_bytes": 8, "id": "out-1",
}},
}
}
func reply(w http.ResponseWriter, status int, v any) {
w.Header().Set("Content-Type", "application/json")
w.WriteHeader(status)
if err := json.NewEncoder(w).Encode(v); err != nil {
return
}
}
func replyError(w http.ResponseWriter, status int, code, message string) {
reply(w, status, map[string]any{"error": map[string]any{"code": code, "message": message, "details": nil}})
}
func (f *fakeAPI) submit(w http.ResponseWriter, r *http.Request) {
var body struct {
Metadata json.RawMessage `json:"metadata"`
}
if err := json.NewDecoder(r.Body).Decode(&body); err != nil {
replyError(w, http.StatusBadRequest, "invalid_request", err.Error())
return
}
key := r.Header.Get("Idempotency-Key")
f.mu.Lock()
reused := f.keys[key]
f.keys[key] = true
if !reused {
f.metadata = body.Metadata
}
f.mu.Unlock()
if reused {
replyError(w, http.StatusUnprocessableEntity, "idempotency_key_reuse", "This Idempotency-Key has already been used.")
return
}
reply(w, http.StatusCreated, f.job(sdk.StatusQueued))
}
func (f *fakeAPI) list(w http.ResponseWriter, _ *http.Request) {
reply(w, http.StatusOK, map[string]any{"jobs": []any{f.job(sdk.StatusSucceeded)}})
}
func (f *fakeAPI) get(w http.ResponseWriter, r *http.Request) {
if r.PathValue("id") != "job-1" {
replyError(w, http.StatusNotFound, "not_found", "No job "+r.PathValue("id")+".")
return
}
reply(w, http.StatusOK, f.job(sdk.StatusSucceeded))
}
func (f *fakeAPI) events(w http.ResponseWriter, _ *http.Request) {
w.Header().Set("Content-Type", "text/event-stream")
frames := "event: status\ndata: {\"status\":\"running\"}\n\n" +
"event: progress\ndata: {\"value\":0.5,\"nodes_done\":1,\"nodes_total\":2}\n\n" +
"event: status\ndata: {\"status\":\"succeeded\"}\n\n"
if _, err := io.WriteString(w, frames); err != nil {
return
}
}
func (f *fakeAPI) content(w http.ResponseWriter, _ *http.Request) {
w.Header().Set("Content-Type", "image/png")
if _, err := io.WriteString(w, "PNG data"); err != nil {
return
}
}
func main() {
_, srv := newFakeAPI()
defer srv.Close()
// Against a local comfy-api-proxy you would pass "http://127.0.0.1:8189".
client, err := sdk.New(
sdk.WithBaseURL(srv.URL),
sdk.WithAPIKey("example-token"),
sdk.WithClientInfo("my-app/1.0"),
)
if err != nil {
log.Fatal(err)
}
fmt.Println("authenticated:", client.Authenticated())
}
Output: authenticated: true
func (*Client) AssetFromBytes ¶
AssetFromBytes uploads an in-memory buffer. An empty filename becomes "upload.bin"; an empty content type is guessed from the filename.
func (*Client) AssetFromFile ¶
AssetFromFile streams a file from disk, hashed and uploaded on commit.
func (*Client) AssetFromReader ¶
AssetFromReader reads r to the end and uploads the bytes.
func (*Client) AssetFromURL ¶
AssetFromURL downloads url and uploads its bytes. The client's bearer token goes with the download only when url is on the client's own origin, and the download is cancelled if the body stalls for the client's timeout.
func (*Client) Authenticated ¶
Authenticated reports whether the client sends a bearer token.
func (*Client) DeleteAsset ¶
DeleteAsset deletes an asset by id.
func (*Client) ListJobs ¶
func (c *Client) ListJobs(ctx context.Context, opts ListOptions) iter.Seq2[JobSummary, error]
ListJobs walks every job the client can see, newest first, a page at a time, stopping at the first error.
func (*Client) Run ¶
Run submits, then polls until the job ends. A job that ends other than succeeded is a *JobFailedError. Bound it with the context.
Example ¶
package main
import (
"context"
"encoding/json"
"fmt"
"io"
"log"
"net/http"
"net/http/httptest"
"sync"
"github.com/regiellis/comfy-api-proxy-go/sdk"
)
// fakeAPI is a minimal in-process Comfy API v2 deployment for the examples:
// one job, one output, single-use idempotency keys, and metadata stored as
// the client sent it.
type fakeAPI struct {
mu sync.Mutex
keys map[string]bool
metadata json.RawMessage
}
func newFakeAPI() (*fakeAPI, *httptest.Server) {
f := &fakeAPI{keys: map[string]bool{}}
mux := http.NewServeMux()
mux.HandleFunc("POST /api/v2/jobs", f.submit)
mux.HandleFunc("GET /api/v2/jobs", f.list)
mux.HandleFunc("GET /api/v2/jobs/{id}", f.get)
mux.HandleFunc("GET /api/v2/jobs/{id}/events", f.events)
mux.HandleFunc("GET /api/v2/assets/{id}/content", f.content)
return f, httptest.NewServer(mux)
}
func (f *fakeAPI) job(status string) map[string]any {
f.mu.Lock()
defer f.mu.Unlock()
return map[string]any{
"id": "job-1", "status": status, "created_at": "2026-10-27T10:00:00Z",
"metadata": f.metadata,
"outputs": []any{map[string]any{
"node_id": "9", "name": "out.png", "type": "image", "content_type": "image/png",
"size_bytes": 8, "id": "out-1",
}},
}
}
func reply(w http.ResponseWriter, status int, v any) {
w.Header().Set("Content-Type", "application/json")
w.WriteHeader(status)
if err := json.NewEncoder(w).Encode(v); err != nil {
return
}
}
func replyError(w http.ResponseWriter, status int, code, message string) {
reply(w, status, map[string]any{"error": map[string]any{"code": code, "message": message, "details": nil}})
}
func (f *fakeAPI) submit(w http.ResponseWriter, r *http.Request) {
var body struct {
Metadata json.RawMessage `json:"metadata"`
}
if err := json.NewDecoder(r.Body).Decode(&body); err != nil {
replyError(w, http.StatusBadRequest, "invalid_request", err.Error())
return
}
key := r.Header.Get("Idempotency-Key")
f.mu.Lock()
reused := f.keys[key]
f.keys[key] = true
if !reused {
f.metadata = body.Metadata
}
f.mu.Unlock()
if reused {
replyError(w, http.StatusUnprocessableEntity, "idempotency_key_reuse", "This Idempotency-Key has already been used.")
return
}
reply(w, http.StatusCreated, f.job(sdk.StatusQueued))
}
func (f *fakeAPI) list(w http.ResponseWriter, _ *http.Request) {
reply(w, http.StatusOK, map[string]any{"jobs": []any{f.job(sdk.StatusSucceeded)}})
}
func (f *fakeAPI) get(w http.ResponseWriter, r *http.Request) {
if r.PathValue("id") != "job-1" {
replyError(w, http.StatusNotFound, "not_found", "No job "+r.PathValue("id")+".")
return
}
reply(w, http.StatusOK, f.job(sdk.StatusSucceeded))
}
func (f *fakeAPI) events(w http.ResponseWriter, _ *http.Request) {
w.Header().Set("Content-Type", "text/event-stream")
frames := "event: status\ndata: {\"status\":\"running\"}\n\n" +
"event: progress\ndata: {\"value\":0.5,\"nodes_done\":1,\"nodes_total\":2}\n\n" +
"event: status\ndata: {\"status\":\"succeeded\"}\n\n"
if _, err := io.WriteString(w, frames); err != nil {
return
}
}
func (f *fakeAPI) content(w http.ResponseWriter, _ *http.Request) {
w.Header().Set("Content-Type", "image/png")
if _, err := io.WriteString(w, "PNG data"); err != nil {
return
}
}
// demoWorkflow is a two-node API-format graph.
func demoWorkflow() *sdk.Workflow {
return sdk.NewWorkflow(map[string]any{
"3": map[string]any{"class_type": "KSampler", "inputs": map[string]any{"seed": 42, "steps": 1}},
"9": map[string]any{"class_type": "SaveImage", "inputs": map[string]any{"images": []any{"3", 0}}},
})
}
func main() {
_, srv := newFakeAPI()
defer srv.Close()
client, err := sdk.New(sdk.WithBaseURL(srv.URL))
if err != nil {
log.Fatal(err)
}
ctx := context.Background()
job, err := client.Run(ctx, demoWorkflow(), sdk.SubmitOptions{})
if err != nil {
log.Fatal(err)
}
for _, o := range job.GetOutputs("9") {
data, err := o.Bytes(ctx, nil)
if err != nil {
log.Fatal(err)
}
fmt.Printf("%s %s %q\n", o.Name(), o.ContentType(), data)
}
}
Output: out.png image/png "PNG data"
func (*Client) Submit ¶
Submit sends a workflow and returns its job. Asset handles in the graph are uploaded (or deduped) first and replaced with core/ASSET references. A 429 carrying Retry-After is retried for up to a minute. Any error from the submission carries the idempotency key it was sent under.
Example ¶
package main
import (
"context"
"encoding/json"
"errors"
"fmt"
"io"
"log"
"net/http"
"net/http/httptest"
"sync"
"github.com/regiellis/comfy-api-proxy-go/sdk"
)
// fakeAPI is a minimal in-process Comfy API v2 deployment for the examples:
// one job, one output, single-use idempotency keys, and metadata stored as
// the client sent it.
type fakeAPI struct {
mu sync.Mutex
keys map[string]bool
metadata json.RawMessage
}
func newFakeAPI() (*fakeAPI, *httptest.Server) {
f := &fakeAPI{keys: map[string]bool{}}
mux := http.NewServeMux()
mux.HandleFunc("POST /api/v2/jobs", f.submit)
mux.HandleFunc("GET /api/v2/jobs", f.list)
mux.HandleFunc("GET /api/v2/jobs/{id}", f.get)
mux.HandleFunc("GET /api/v2/jobs/{id}/events", f.events)
mux.HandleFunc("GET /api/v2/assets/{id}/content", f.content)
return f, httptest.NewServer(mux)
}
func (f *fakeAPI) job(status string) map[string]any {
f.mu.Lock()
defer f.mu.Unlock()
return map[string]any{
"id": "job-1", "status": status, "created_at": "2026-10-27T10:00:00Z",
"metadata": f.metadata,
"outputs": []any{map[string]any{
"node_id": "9", "name": "out.png", "type": "image", "content_type": "image/png",
"size_bytes": 8, "id": "out-1",
}},
}
}
func reply(w http.ResponseWriter, status int, v any) {
w.Header().Set("Content-Type", "application/json")
w.WriteHeader(status)
if err := json.NewEncoder(w).Encode(v); err != nil {
return
}
}
func replyError(w http.ResponseWriter, status int, code, message string) {
reply(w, status, map[string]any{"error": map[string]any{"code": code, "message": message, "details": nil}})
}
func (f *fakeAPI) submit(w http.ResponseWriter, r *http.Request) {
var body struct {
Metadata json.RawMessage `json:"metadata"`
}
if err := json.NewDecoder(r.Body).Decode(&body); err != nil {
replyError(w, http.StatusBadRequest, "invalid_request", err.Error())
return
}
key := r.Header.Get("Idempotency-Key")
f.mu.Lock()
reused := f.keys[key]
f.keys[key] = true
if !reused {
f.metadata = body.Metadata
}
f.mu.Unlock()
if reused {
replyError(w, http.StatusUnprocessableEntity, "idempotency_key_reuse", "This Idempotency-Key has already been used.")
return
}
reply(w, http.StatusCreated, f.job(sdk.StatusQueued))
}
func (f *fakeAPI) list(w http.ResponseWriter, _ *http.Request) {
reply(w, http.StatusOK, map[string]any{"jobs": []any{f.job(sdk.StatusSucceeded)}})
}
func (f *fakeAPI) get(w http.ResponseWriter, r *http.Request) {
if r.PathValue("id") != "job-1" {
replyError(w, http.StatusNotFound, "not_found", "No job "+r.PathValue("id")+".")
return
}
reply(w, http.StatusOK, f.job(sdk.StatusSucceeded))
}
func (f *fakeAPI) events(w http.ResponseWriter, _ *http.Request) {
w.Header().Set("Content-Type", "text/event-stream")
frames := "event: status\ndata: {\"status\":\"running\"}\n\n" +
"event: progress\ndata: {\"value\":0.5,\"nodes_done\":1,\"nodes_total\":2}\n\n" +
"event: status\ndata: {\"status\":\"succeeded\"}\n\n"
if _, err := io.WriteString(w, frames); err != nil {
return
}
}
func (f *fakeAPI) content(w http.ResponseWriter, _ *http.Request) {
w.Header().Set("Content-Type", "image/png")
if _, err := io.WriteString(w, "PNG data"); err != nil {
return
}
}
// demoWorkflow is a two-node API-format graph.
func demoWorkflow() *sdk.Workflow {
return sdk.NewWorkflow(map[string]any{
"3": map[string]any{"class_type": "KSampler", "inputs": map[string]any{"seed": 42, "steps": 1}},
"9": map[string]any{"class_type": "SaveImage", "inputs": map[string]any{"images": []any{"3", 0}}},
})
}
func main() {
_, srv := newFakeAPI()
defer srv.Close()
client, err := sdk.New(sdk.WithBaseURL(srv.URL))
if err != nil {
log.Fatal(err)
}
ctx := context.Background()
job, err := client.Submit(ctx, demoWorkflow(), sdk.SubmitOptions{IdempotencyKey: "order-1234"})
if err != nil {
log.Fatal(err)
}
fmt.Println("submitted:", job.ID(), job.Status())
// Keys are single-use. A second submit under the same key is refused,
// and the error carries the key so the caller can look the job up.
_, err = client.Submit(ctx, demoWorkflow(), sdk.SubmitOptions{IdempotencyKey: "order-1234"})
var apiErr *sdk.APIError
if errors.Is(err, sdk.ErrIdempotencyKeyReuse) && errors.As(err, &apiErr) {
fmt.Println("refused:", apiErr.HTTPStatus, apiErr.Code, apiErr.IdempotencyKey)
}
if err := job.Wait(ctx); err != nil {
log.Fatal(err)
}
fmt.Println("finished:", job.Status())
}
Output: submitted: job-1 queued refused: 422 idempotency_key_reuse order-1234 finished: succeeded
type DownloadURL ¶
DownloadURL is where the asset's bytes can be fetched, with its expiry when the server issued a signed URL.
type Event ¶
type Event interface {
// contains filtered or unexported methods
}
Event is one item from a job's live stream: *Progress, *Preview, *OutputReady, *StatusChange, or *Log.
type Job ¶
type Job struct {
// contains filtered or unexported fields
}
Job is a submitted job. Its fields are the snapshot from the last call that returned it; Refresh, Wait, and Cancel update them. Safe for concurrent use.
func (*Job) Cancel ¶
Cancel asks the server to cancel. A running job reads canceling until the interrupt lands; Wait for the terminal state.
func (*Job) Events ¶
Events streams the job's live events until a terminal status. The stream is best effort and poll-backed: a dropped connection reconnects, a stream that ends without a terminal status falls back to GET /jobs/{id}, and a server without the endpoint (501) ends the iteration quietly. The last event is always a terminal *StatusChange unless an error ends it first.
Example ¶
package main
import (
"context"
"encoding/json"
"fmt"
"io"
"log"
"net/http"
"net/http/httptest"
"sync"
"github.com/regiellis/comfy-api-proxy-go/sdk"
)
// fakeAPI is a minimal in-process Comfy API v2 deployment for the examples:
// one job, one output, single-use idempotency keys, and metadata stored as
// the client sent it.
type fakeAPI struct {
mu sync.Mutex
keys map[string]bool
metadata json.RawMessage
}
func newFakeAPI() (*fakeAPI, *httptest.Server) {
f := &fakeAPI{keys: map[string]bool{}}
mux := http.NewServeMux()
mux.HandleFunc("POST /api/v2/jobs", f.submit)
mux.HandleFunc("GET /api/v2/jobs", f.list)
mux.HandleFunc("GET /api/v2/jobs/{id}", f.get)
mux.HandleFunc("GET /api/v2/jobs/{id}/events", f.events)
mux.HandleFunc("GET /api/v2/assets/{id}/content", f.content)
return f, httptest.NewServer(mux)
}
func (f *fakeAPI) job(status string) map[string]any {
f.mu.Lock()
defer f.mu.Unlock()
return map[string]any{
"id": "job-1", "status": status, "created_at": "2026-10-27T10:00:00Z",
"metadata": f.metadata,
"outputs": []any{map[string]any{
"node_id": "9", "name": "out.png", "type": "image", "content_type": "image/png",
"size_bytes": 8, "id": "out-1",
}},
}
}
func reply(w http.ResponseWriter, status int, v any) {
w.Header().Set("Content-Type", "application/json")
w.WriteHeader(status)
if err := json.NewEncoder(w).Encode(v); err != nil {
return
}
}
func replyError(w http.ResponseWriter, status int, code, message string) {
reply(w, status, map[string]any{"error": map[string]any{"code": code, "message": message, "details": nil}})
}
func (f *fakeAPI) submit(w http.ResponseWriter, r *http.Request) {
var body struct {
Metadata json.RawMessage `json:"metadata"`
}
if err := json.NewDecoder(r.Body).Decode(&body); err != nil {
replyError(w, http.StatusBadRequest, "invalid_request", err.Error())
return
}
key := r.Header.Get("Idempotency-Key")
f.mu.Lock()
reused := f.keys[key]
f.keys[key] = true
if !reused {
f.metadata = body.Metadata
}
f.mu.Unlock()
if reused {
replyError(w, http.StatusUnprocessableEntity, "idempotency_key_reuse", "This Idempotency-Key has already been used.")
return
}
reply(w, http.StatusCreated, f.job(sdk.StatusQueued))
}
func (f *fakeAPI) list(w http.ResponseWriter, _ *http.Request) {
reply(w, http.StatusOK, map[string]any{"jobs": []any{f.job(sdk.StatusSucceeded)}})
}
func (f *fakeAPI) get(w http.ResponseWriter, r *http.Request) {
if r.PathValue("id") != "job-1" {
replyError(w, http.StatusNotFound, "not_found", "No job "+r.PathValue("id")+".")
return
}
reply(w, http.StatusOK, f.job(sdk.StatusSucceeded))
}
func (f *fakeAPI) events(w http.ResponseWriter, _ *http.Request) {
w.Header().Set("Content-Type", "text/event-stream")
frames := "event: status\ndata: {\"status\":\"running\"}\n\n" +
"event: progress\ndata: {\"value\":0.5,\"nodes_done\":1,\"nodes_total\":2}\n\n" +
"event: status\ndata: {\"status\":\"succeeded\"}\n\n"
if _, err := io.WriteString(w, frames); err != nil {
return
}
}
func (f *fakeAPI) content(w http.ResponseWriter, _ *http.Request) {
w.Header().Set("Content-Type", "image/png")
if _, err := io.WriteString(w, "PNG data"); err != nil {
return
}
}
// demoWorkflow is a two-node API-format graph.
func demoWorkflow() *sdk.Workflow {
return sdk.NewWorkflow(map[string]any{
"3": map[string]any{"class_type": "KSampler", "inputs": map[string]any{"seed": 42, "steps": 1}},
"9": map[string]any{"class_type": "SaveImage", "inputs": map[string]any{"images": []any{"3", 0}}},
})
}
func main() {
_, srv := newFakeAPI()
defer srv.Close()
client, err := sdk.New(sdk.WithBaseURL(srv.URL))
if err != nil {
log.Fatal(err)
}
ctx := context.Background()
job, err := client.Submit(ctx, demoWorkflow(), sdk.SubmitOptions{})
if err != nil {
log.Fatal(err)
}
for ev, err := range job.Events(ctx) {
if err != nil {
log.Fatal(err)
}
switch e := ev.(type) {
case *sdk.StatusChange:
fmt.Println("status", e.Status)
case *sdk.Progress:
fmt.Printf("progress %.0f%%\n", e.Value*100)
}
}
}
Output: status running progress 50% status succeeded
func (*Job) Failure ¶
Failure is the server's account of a failed job, nil otherwise. The returned value is a copy.
func (*Job) GetOutputs ¶
GetOutputs are the outputs one node produced.
func (*Job) Metadata ¶
Metadata is the job's labels; empty when it has none, or when the server sends metadata that is neither a string map nor a JSON-encoded string map.
func (*Job) Progress ¶
func (j *Job) Progress() *JobProgress
Progress is a copy of the last progress snapshot, nil when the server sent none.
func (*Job) QueuePosition ¶
QueuePosition is the job's place in the queue while queued.
type JobError ¶
type JobError struct {
Code string `json:"code"`
Message string `json:"message"`
NodeID *string `json:"node_id"`
ClassType *string `json:"class_type"`
Traceback *string `json:"traceback"`
}
JobError is the server's account of why a job failed.
type JobFailedError ¶
type JobFailedError struct {
JobID string
Status string
// Err is the server's account of the failure, nil when it gave none.
Err *JobError
}
JobFailedError reports a job that reached a terminal state other than succeeded. errors.Is(err, ErrJobFailed) matches it.
func (*JobFailedError) Error ¶
func (e *JobFailedError) Error() string
Error names the job and the status it ended in.
type JobProgress ¶
type JobProgress struct {
Value float64 `json:"value"`
NodesDone int `json:"nodes_done"`
NodesTotal int `json:"nodes_total"`
CurrentNode *string `json:"current_node"`
CurrentNodeClass *string `json:"current_node_class"`
Step *int `json:"step"`
Steps *int `json:"steps"`
Message *string `json:"message"`
}
JobProgress is the latest progress snapshot on a job.
type JobSummary ¶
type JobSummary struct {
ID string
Status string
CreateTime *time.Time
UpdateTime *time.Time
DeploymentID *string
Metadata map[string]string
// Data is the item as the server sent it, for fields not lifted above.
Data map[string]any
}
JobSummary is one entry of the job list.
type JobWorkflow ¶
JobWorkflow is the graph a job ran with. Format is "api" for an executed graph or "save" for the original authoring workflow.
type ListModelsOptions ¶
ListModelsOptions page the catalog.
type ListOptions ¶
type ListOptions struct {
// Metadata keeps only jobs carrying every pair. The server filters by
// it, and the SDK filters again locally. With WithProxyMetadata only the
// local filter runs, over the jobs the server returns.
Metadata map[string]string
// Limit is the page size the server is asked for; zero leaves it unset.
Limit int
}
ListOptions filter the job list.
type ModelPage ¶
type ModelPage struct {
Data []CatalogModel
// HasMore is whether another page exists; walk on it, never on a short
// Data.
HasMore bool
NextCursor string
// Limit is the page size served; a request above 100 is clamped.
Limit int
RequestID string
}
ModelPage is one page of the catalog.
type Models ¶
type Models struct {
// contains filtered or unexported fields
}
Models runs hosted models on Comfy Router (client.Models). It shares the client's key and follows its RetryPolicy.
func (*Models) Handle ¶
func (m *Models) Handle(model, requestID string) (*RequestHandle, error)
Handle rebuilds a handle for a request submitted earlier.
func (*Models) List ¶
func (m *Models) List(ctx context.Context, opts ListModelsOptions) iter.Seq2[CatalogModel, error]
List walks the whole catalog, page by page, stopping at the first error.
func (*Models) Retry ¶
func (m *Models) Retry() RetryPolicy
Retry is the policy Router calls fail under.
func (*Models) Run ¶
func (m *Models) Run(ctx context.Context, model string, args map[string]any, opts RunOptions) (RunOutput, error)
Run invokes a model and waits for its output. It is billed. A failure the Router may have acted on (a 5xx, a dropped connection) is retried only when the policy allows it; retries reuse one Idempotency-Key, so a retry cannot bill twice. If a retry is refused as a key reuse after an earlier attempt may have claimed the key, the earlier failure is returned with ResendRefused set: the generation may exist, so collect it under the key.
func (*Models) RunDetailed ¶
func (m *Models) RunDetailed(ctx context.Context, model string, args map[string]any, opts RunOptions) (RunResult, error)
RunDetailed is Run with Router's disclosures beside the output.
func (*Models) Schema ¶
Schema fetches a model's schemas. Pass the ETag from an earlier call to get Unchanged instead of the document again.
func (*Models) Submit ¶
func (m *Models) Submit(ctx context.Context, model string, args map[string]any, opts RunOptions) (*RequestHandle, error)
Submit queues a model run and returns its handle. It is billed when it runs. Collect with Get, follow with Updates, or stop with Cancel.
func (*Models) Subscribe ¶
func (m *Models) Subscribe(ctx context.Context, model string, args map[string]any, opts RunOptions, onUpdate func(QueueUpdate)) (RunOutput, error)
Subscribe submits, follows the queue (passing each change to onUpdate when it is non-nil), and collects the output. When ctx ends first, the request is cancelled on a best-effort basis before the error returns, so an abandoned wait does not leave a generation running.
type Option ¶
type Option func(*options)
Option configures New.
func WithAPIKey ¶
WithAPIKey sets the bearer token. It wins over COMFY_API_KEY. An empty value counts as not given.
func WithBaseURL ¶
WithBaseURL targets a deployment, winning over COMFY_BASE_URL. An empty value counts as not given.
func WithClientInfo ¶
WithClientInfo appends "app/<info>" to the User-Agent.
func WithHTTPClient ¶
WithHTTPClient replaces the HTTP client. Its timeouts then apply as set, to every call including synchronous model runs, so a response-header limit on it must allow for a whole generation. The SDK still strips the bearer token on a redirect that leaves the configured origins.
func WithProxyMetadata ¶
func WithProxyMetadata() Option
WithProxyMetadata encodes job labels as a JSON string for comfy-api-proxy. ListJobs filters labels locally, since the proxy has no label-map filter. Omit this option for deployments that accept metadata objects. Comfy Cloud refuses labels for now with an *APIError whose Code is "metadata_not_supported".
Example ¶
package main
import (
"context"
"encoding/json"
"fmt"
"io"
"log"
"net/http"
"net/http/httptest"
"sync"
"github.com/regiellis/comfy-api-proxy-go/sdk"
)
// fakeAPI is a minimal in-process Comfy API v2 deployment for the examples:
// one job, one output, single-use idempotency keys, and metadata stored as
// the client sent it.
type fakeAPI struct {
mu sync.Mutex
keys map[string]bool
metadata json.RawMessage
}
func newFakeAPI() (*fakeAPI, *httptest.Server) {
f := &fakeAPI{keys: map[string]bool{}}
mux := http.NewServeMux()
mux.HandleFunc("POST /api/v2/jobs", f.submit)
mux.HandleFunc("GET /api/v2/jobs", f.list)
mux.HandleFunc("GET /api/v2/jobs/{id}", f.get)
mux.HandleFunc("GET /api/v2/jobs/{id}/events", f.events)
mux.HandleFunc("GET /api/v2/assets/{id}/content", f.content)
return f, httptest.NewServer(mux)
}
func (f *fakeAPI) job(status string) map[string]any {
f.mu.Lock()
defer f.mu.Unlock()
return map[string]any{
"id": "job-1", "status": status, "created_at": "2026-10-27T10:00:00Z",
"metadata": f.metadata,
"outputs": []any{map[string]any{
"node_id": "9", "name": "out.png", "type": "image", "content_type": "image/png",
"size_bytes": 8, "id": "out-1",
}},
}
}
func reply(w http.ResponseWriter, status int, v any) {
w.Header().Set("Content-Type", "application/json")
w.WriteHeader(status)
if err := json.NewEncoder(w).Encode(v); err != nil {
return
}
}
func replyError(w http.ResponseWriter, status int, code, message string) {
reply(w, status, map[string]any{"error": map[string]any{"code": code, "message": message, "details": nil}})
}
func (f *fakeAPI) submit(w http.ResponseWriter, r *http.Request) {
var body struct {
Metadata json.RawMessage `json:"metadata"`
}
if err := json.NewDecoder(r.Body).Decode(&body); err != nil {
replyError(w, http.StatusBadRequest, "invalid_request", err.Error())
return
}
key := r.Header.Get("Idempotency-Key")
f.mu.Lock()
reused := f.keys[key]
f.keys[key] = true
if !reused {
f.metadata = body.Metadata
}
f.mu.Unlock()
if reused {
replyError(w, http.StatusUnprocessableEntity, "idempotency_key_reuse", "This Idempotency-Key has already been used.")
return
}
reply(w, http.StatusCreated, f.job(sdk.StatusQueued))
}
func (f *fakeAPI) list(w http.ResponseWriter, _ *http.Request) {
reply(w, http.StatusOK, map[string]any{"jobs": []any{f.job(sdk.StatusSucceeded)}})
}
func (f *fakeAPI) get(w http.ResponseWriter, r *http.Request) {
if r.PathValue("id") != "job-1" {
replyError(w, http.StatusNotFound, "not_found", "No job "+r.PathValue("id")+".")
return
}
reply(w, http.StatusOK, f.job(sdk.StatusSucceeded))
}
func (f *fakeAPI) events(w http.ResponseWriter, _ *http.Request) {
w.Header().Set("Content-Type", "text/event-stream")
frames := "event: status\ndata: {\"status\":\"running\"}\n\n" +
"event: progress\ndata: {\"value\":0.5,\"nodes_done\":1,\"nodes_total\":2}\n\n" +
"event: status\ndata: {\"status\":\"succeeded\"}\n\n"
if _, err := io.WriteString(w, frames); err != nil {
return
}
}
func (f *fakeAPI) content(w http.ResponseWriter, _ *http.Request) {
w.Header().Set("Content-Type", "image/png")
if _, err := io.WriteString(w, "PNG data"); err != nil {
return
}
}
// demoWorkflow is a two-node API-format graph.
func demoWorkflow() *sdk.Workflow {
return sdk.NewWorkflow(map[string]any{
"3": map[string]any{"class_type": "KSampler", "inputs": map[string]any{"seed": 42, "steps": 1}},
"9": map[string]any{"class_type": "SaveImage", "inputs": map[string]any{"images": []any{"3", 0}}},
})
}
func main() {
fake, srv := newFakeAPI()
defer srv.Close()
client, err := sdk.New(sdk.WithBaseURL(srv.URL), sdk.WithProxyMetadata())
if err != nil {
log.Fatal(err)
}
ctx := context.Background()
job, err := client.Submit(ctx, demoWorkflow(), sdk.SubmitOptions{
Metadata: map[string]string{"project": "demo", "shot": "12"},
})
if err != nil {
log.Fatal(err)
}
fake.mu.Lock()
fmt.Println("sent:", string(fake.metadata))
fake.mu.Unlock()
fmt.Println("labels:", job.Metadata())
for s, err := range client.ListJobs(ctx, sdk.ListOptions{Metadata: map[string]string{"project": "demo"}}) {
if err != nil {
log.Fatal(err)
}
fmt.Println("listed:", s.ID, s.Status)
}
}
Output: sent: "{\"project\":\"demo\",\"shot\":\"12\"}" labels: map[project:demo shot:12] listed: job-1 succeeded
func WithRetry ¶
func WithRetry(p RetryPolicy) Option
WithRetry sets the policy client.Models calls fail under. It does not govern Submit and Run, which follow the server's Retry-After.
func WithRouterBaseURL ¶
WithRouterBaseURL targets another Comfy Router, winning over COMFY_ROUTER_BASE_URL.
func WithTimeout ¶
WithTimeout bounds connecting and waiting for response headers, and how long a streamed body may sit idle. It is not a cap on a whole download. The default is 30 seconds. Synchronous model runs keep a 600 second limit on response headers, since Router answers only when the generation is done.
type Output ¶
type Output struct {
// contains filtered or unexported fields
}
Output is one file a job produced.
func (*Output) ContentType ¶
ContentType is the output's media type.
func (*Output) DownloadURL ¶
func (o *Output) DownloadURL(ctx context.Context) (DownloadURL, error)
DownloadURL resolves a URL for the output's bytes: a signed URL with its expiry on Comfy Cloud, the content endpoint itself on a self-hosted proxy.
func (*Output) ToFile ¶
ToFile streams the output to path, creating or truncating it. A failed download removes the partial file.
func (*Output) ToWriter ¶
ToWriter streams the output (or rng of it, when non-nil) into w and reports the bytes written.
func (*Output) URLExpiresAt ¶
URLExpiresAt is when the output's content URL stops working.
type OutputReady ¶
type OutputReady struct{ Output *Output }
OutputReady carries an output the moment it is committed.
type Progress ¶
type Progress struct {
Value float64
Message *string
NodesDone *int
NodesTotal *int
CurrentNode *string
Step *int
Steps *int
}
Progress is a full progress snapshot, so a dropped one costs nothing.
type QueueUpdate ¶
type QueueUpdate struct {
RequestID string
Status string
QueuePosition *int
ErrorType string
// RetryAfter is the pace the server asked for, in seconds.
RetryAfter *int
Raw map[string]any
}
QueueUpdate is one observed state of a queued request.
func (QueueUpdate) IsCompleted ¶
func (u QueueUpdate) IsCompleted() bool
IsCompleted reports a finished request, failed or not.
type Range ¶
type Range struct{ Start, End int64 }
Range is an inclusive byte range for a partial download.
type RequestHandle ¶
type RequestHandle struct {
// contains filtered or unexported fields
}
RequestHandle is a queued model request.
func (*RequestHandle) Cancel ¶
func (h *RequestHandle) Cancel(ctx context.Context) (QueueUpdate, error)
Cancel asks the queue to stop the request.
func (*RequestHandle) Get ¶
func (h *RequestHandle) Get(ctx context.Context) (RunOutput, error)
Get waits for the request to complete, then collects its output. A completion that names an error_type is returned as that Router error.
func (*RequestHandle) Model ¶
func (h *RequestHandle) Model() string
Model is the model id the request runs.
func (*RequestHandle) RequestID ¶
func (h *RequestHandle) RequestID() string
RequestID is the queue's id for the request.
func (*RequestHandle) Status ¶
func (h *RequestHandle) Status(ctx context.Context) (QueueUpdate, error)
Status reads the request's current state.
func (*RequestHandle) String ¶
func (h *RequestHandle) String() string
String reports the model and request id.
func (*RequestHandle) Updates ¶
func (h *RequestHandle) Updates(ctx context.Context) iter.Seq2[QueueUpdate, error]
Updates polls the request, yielding each change of status or position, and ends after COMPLETED. Polls follow the queue's Retry-After (capped at a minute), else a schedule from half a second to five. Bound it with ctx.
type RetryPolicy ¶
type RetryPolicy struct {
// MaxElapsed bounds the whole retry window; zero disables retrying.
MaxElapsed time.Duration
// InitialBackoff, BackoffFactor, and MaxBackoff shape the exponential
// backoff used when the server names no Retry-After.
InitialBackoff time.Duration
BackoffFactor float64
MaxBackoff time.Duration
// Jitter draws each wait uniformly below its ceiling.
Jitter bool
// RetryPossiblyInFlight also retries a 5xx or a dropped connection.
RetryPossiblyInFlight bool
// RetryCollectable collects a still-running generation under its key.
RetryCollectable bool
// CollectMaxElapsed bounds collecting; generations can take minutes.
CollectMaxElapsed time.Duration
}
RetryPolicy decides which failed Router calls (client.Models) are retried and for how long. It does not govern the workflow surface (Submit, Run), whose 429 handling follows the server's Retry-After.
Retried without asking: a 429 that names Retry-After, and a failure that never reached the server (refused connection, connect timeout). A 5xx or a connection dropped mid-request may have run, and a model run is billed, so those retry only with RetryPossiblyInFlight. A run the Router is still working on (409 concurrency_limit_exceeded or 504 deadline_exceeded, each with Retry-After) is collected under the same key on its own longer budget.
func (RetryPolicy) Validate ¶
func (p RetryPolicy) Validate() error
Validate reports a policy that cannot be followed.
type RunOptions ¶
type RunOptions struct {
// IdempotencyKey is minted fresh when empty. Reuse it to retry a run
// without paying twice.
IdempotencyKey string
// ModelProvider routes to an alternate provider, translating the body.
ModelProvider string
// StrictMode refuses translation that would drop fields.
StrictMode *bool
// FallbackProvider is "true", "false", or a provider to fall back to.
FallbackProvider string
}
RunOptions are the optional parts of a model run.
type RunOutput ¶
type RunOutput struct {
JSON map[string]any
Binary *BinaryResult
}
RunOutput is a model's native output: JSON for a partner that answers JSON, Binary for one that answers bytes. Exactly one is set.
type RunResult ¶
type RunResult struct {
Output RunOutput
// ServingProvider is the provider that served the call after a
// fallback succeeded; nil means the requested provider served it.
ServingProvider *string
// DroppedParams names native fields translation could not carry.
DroppedParams []string
// Replayed means the response came from the key's record and was not
// run, or billed, again.
Replayed bool
RequestID string
// CreditsUsed is what Router priced the run at, as its decimal string.
// Nil means not reported, never free; "0" is a real reported cost.
CreditsUsed *string
}
RunResult is a run's output plus what Router disclosed about it.
type SchemaResult ¶
type SchemaResult struct {
// Unchanged is true on a 304: the document is the one the etag names.
Unchanged bool
// Document is a standalone OpenAPI document, nil when Unchanged.
Document map[string]any
ETag string
RequestID string
}
SchemaResult is a model's input and output schemas.
type StatusChange ¶
StatusChange is a status transition; the stream ends after a terminal one.
type SubmitOptions ¶
type SubmitOptions struct {
// PartnerAPIKey authenticates partner (API) nodes in the workflow, sent
// as extra_data.api_key_comfy_org. Unrelated to the client's own key.
PartnerAPIKey string
// IdempotencyKey is minted fresh when empty. A reused key is rejected
// (ErrIdempotencyKeyReuse), not replayed.
IdempotencyKey string
// Metadata labels the job. Use WithProxyMetadata when targeting
// comfy-api-proxy, which requires string metadata instead of an object.
Metadata map[string]string
}
SubmitOptions are the optional parts of a submission.
type TransportError ¶
type TransportError struct {
IdempotencyKey string
// ResendRefused: see APIError.ResendRefused.
ResendRefused bool
Err error
}
TransportError wraps a failure that never produced a response: refused connection, timeout, a stream cut mid-body. It keeps the idempotency key a submit was sent under. Whether the server saw the request is unknown, so poll or list before resubmitting under the same key.
func (*TransportError) Error ¶
func (e *TransportError) Error() string
Error is the underlying failure's message.
func (*TransportError) Unwrap ¶
func (e *TransportError) Unwrap() error
Unwrap returns the underlying failure, so errors.Is can find ErrIdleTimeout or context.Canceled.
type ValidationErrorDetail ¶
ValidationErrorDetail is one entry of a Router validation response.
func (ValidationErrorDetail) Location ¶
func (d ValidationErrorDetail) Location() string
Location joins Loc into a dotted path such as "body.prompt".
type Workflow ¶
Workflow is an API-format graph: node id to {class_type, inputs}.
func WorkflowFromFile ¶
WorkflowFromFile reads an API-format graph from disk.
func WorkflowFromJSON ¶
WorkflowFromJSON parses an API-format graph. Numbers stay exact, so a 64-bit seed survives.
Example ¶
package main
import (
"encoding/json"
"fmt"
"log"
"github.com/regiellis/comfy-api-proxy-go/sdk"
)
func main() {
// A seed above 2^53 would lose precision as a float64. WorkflowFromJSON
// keeps every number exact, so it reaches the server unchanged.
wf, err := sdk.WorkflowFromJSON([]byte(`{"3": {"class_type": "KSampler", "inputs": {"seed": 18446744073709551615}}}`))
if err != nil {
log.Fatal(err)
}
wf.SetInput("3", "steps", 20)
out, err := json.Marshal(wf.Graph)
if err != nil {
log.Fatal(err)
}
fmt.Println(string(out))
}
Output: {"3":{"class_type":"KSampler","inputs":{"seed":18446744073709551615,"steps":20}}}
func (*Workflow) RemoveNode ¶
RemoveNode deletes a node. When the removed node had exactly one linked input, links that pointed at it are rewired to that input's source, so a pass-through node (an upscale, a preview) can be cut out; otherwise links to it are dropped.