API Stable Diffusion

Modail stòr-fosgailte àbhaisteach an gnìomhachais le gnàthachadh farsaing

✓ Stòr-fosgailte

✓ Gnàthaichte

✓ ControlNet

✓ Taic LoRA

Dearbh-aithneachadh

Gus cothrom fhaighinn air Stable Diffusion tro API Doitong, cleachd an iuchair API Doitong agad. Cuir i an sàs ann am mùthadh GraphQL no ann am bannan-cinn an API REST.

Cudromach: Cùm an iuchair API Doitong agad sàbhailte agus na leig fhaicinn i ann an còd taobh a' chliaint gu bràth. Dèan gairmean API bhon fhrithealaiche cùil agad an-còmhnaidh.
// GraphQL Header
{
  "Authorization": "Bearer YOUR_API_KEY"
}

// REST Header
"X-API-Key": "YOUR_API_KEY"

Toiseach Luath

Tòisich le Stable Diffusion API ann am beagan mhionaidean. Lean na ceumannan sìmplidh seo gus a' chiad text to image agad a chruthachadh.

Ceum 1: Faigh an Iuchair API agad

Clàraich airson cunntas Doitong agus rach chun deas-bhòrd agad gus iuchair API a chruthachadh.

Ceum 2: Dèan a' Chiad Iarrtas agad

Cleachd fear de na h-eisimpleirean còda gu h-ìosal gus a' chiad ghairm API agad a dhèanamh.

curl -X POST https://api.doitong.com/graphql \
  -H "Content-Type: application/json" \
  -H "Authorization: Bearer YOUR_API_KEY" \
  -d '{
    "query": "mutation Generate($input: GenerateInput!) { generate(input: $input) { id status type provider url metadata creditCost } }",
    "variables": {
      "input": {
        "type": "IMAGE",
        "provider": "stable-diffusion",
        "input": {
          "text": "A futuristic city with flying cars and neon lights"
        },
        "options": {
          "width": 1024,
          "height": 1024
        }
      }
    }
  }'
const response = await fetch('https://api.doitong.com/graphql', {
  method: 'POST',
  headers: {
    'Content-Type': 'application/json',
    'Authorization': 'Bearer YOUR_API_KEY'
  },
  body: JSON.stringify({
    query: `
      mutation GenerateImage($input: ImageGenerationInput!) {
        generateImage(input: $input) {
          id
          url
          width
          height
        }
      }
    `,
    variables: {
      input: {
        service: 'stable-diffusion',
        prompt: 'A futuristic city with flying cars and neon lights',
        width: 1024,
        height: 1024
      }
    }
  })
});

const data = await response.json();
console.log('Image:', data.data.generateImage);
import requests
import json

url = "https://api.doitong.com/graphql"
headers = {
    "Content-Type": "application/json",
    "Authorization": "Bearer YOUR_API_KEY"
}

query = """
mutation Generate($input: GenerateInput!) {
  generate(input: $input) {
    id
    status
    type
    provider
    url
    metadata
    creditCost
  }
}
"""

variables = {
    "input": {
        "type": "IMAGE",
        "provider": "stable-diffusion",
        "input": {
            "text": "A futuristic city with flying cars and neon lights"
        },
        "options": {
            "width": 1024,
            "height": 1024
        }
    }
}

response = requests.post(url, json={
    "query": query,
    "variables": variables
}, headers=headers)

data = response.json()
print("Result:", data["data"]["generate"])
mutation Generate($input: GenerateInput!) {
  generate(input: $input) {
    id
    status
    type
    provider
    url
    metadata
    creditCost
    createdAt
  }
}

# Variables
{
  "input": {
    "type": "IMAGE",
    "provider": "stable-diffusion",
    "input": {
      "text": "A futuristic city with flying cars and neon lights"
    },
    "options": {
      "width": 1024,
      "height": 1024,
      "version": "sd-2.1",
      "quality": "high"
    }
  }
}

Prìsean

Tha Stable Diffusion API a' cleachdadh modail prìse stèidhichte air creideasan. Thèid creideasan a chleachdadh a rèir cho iomadh-fhillte 's a tha an t-susbaint agus dè cho fada 's a mhaireas i.

Feart Creideasan Tuairisgeul
Dùmhlachd-bhreacaidh Àbhaisteach 10-20 Creideasan 512x512 gu 1024x1024 piogsailean
Àrd-dhùmhlachd-bhreacaidh 30-50 Creideasan 2048x2048 piogsailean agus os a chionn

Puingean-crìche API

Tha Stable Diffusion API ri fhaighinn tron phuing-chrìche GraphQL aonaichte againn.

Puing-chrìche GraphQL

POST https://api.doitong.com/graphql

Puing-chrìche REST

POST https://api.doitong.com/v1/text_to_image

Paramaidirean

Paramaidirean a tha rim faighinn airson iarrtasan Stable Diffusion API:

Paramaid Seòrsa Riatanach Tuairisgeul
service String Yes Aithneadair seirbheis: "stable-diffusion"
prompt String Yes Tuairisgeul teacsa air na tha ri chruthachadh
width Integer No Leud an deilbh ann am piogsailean (bun-tomhas: 1024)
height Integer No Àirde an deilbh ann am piogsailean (bun-tomhas: 1024)
version String No Model version: "sd-xl", "sd-2.1"
webhookUrl String No URL airson fiosan crìochnachaidh fhaighinn

Cruth na Freagairt

Tha a h-uile freagairt API a' leantainn cruth cunbhalach:

Freagairt Shoirbheachail

{
  "data": {
    "generateimage": {
      "id": "abc123xyz",
      "status": "processing",
      "url": null,
      "webhookUrl": "https://your-webhook.com/callback",
      "createdAt": "2024-01-01T00:00:00Z"
    }
  }
}

Freagairt Chrìochnaichte

{
  "data": {
    "generateimage": {
      "id": "abc123xyz",
      "status": "completed",
      "url": "https://cdn.doitong.com/outputs/abc123xyz.jpg",
      "duration": null,
      "createdAt": "2024-01-01T00:00:00Z"
    }
  }
}

Làimhseachadh Mhearachdan

Tha an API a' cleachdadh còdan inbhe HTTP àbhaisteach agus a' tilleadh teachdaireachdan mearachd mionaideach.

Còdan Mearachd Cumanta

Còd Inbhe Seòrsa Mearachd Tuairisgeul
400 Bad Request Invalid parameters or malformed request
401 Unauthorized Missing or invalid API key
402 Payment Required Insufficient credits
429 Too Many Requests Rate limit exceeded
500 Internal Server Error Server error, please retry

Cruth Freagairt Mearachd

{
  "errors": [
    {
      "message": "Insufficient credits for this operation",
      "extensions": {
        "code": "INSUFFICIENT_CREDITS",
        "creditsRequired": 100,
        "creditsAvailable": 50
      }
    }
  ]
}

Webhooks

Faigh fiosan fìor-ùine nuair a bhios cruthachadh text to image deiseil.

A' rèiteachadh Webhooks

Include a <code>webhookUrl</code> parameter in your request to receive a POST notification when processing is complete.

Payload Webhook

{
  "id": "abc123xyz",
  "status": "completed",
  "url": "https://cdn.doitong.com/outputs/abc123xyz.jpg",
  "service": "stable-diffusion",
  "createdAt": "2024-01-01T00:00:00Z",
  "completedAt": "2024-01-01T00:01:00Z",
  "metadata": {
    "duration": null,
    "width": 1920,
    "height": 1080
  }
}

Tèarainteachd Webhook

Tha bann-cinn ainm-sgrìobhte anns a h-uile iarrtas webhook airson dearbhadh:

X-Doitong-Signature: sha256=abc123...

Crìochan Luaths

Gus dèanamh cinnteach gu bheil an siostam cothromach agus seasmhach, tha na crìochan luaths seo an sàs:

Plana Iarrtasan/Mionaid Obraichean aig an aon àm Crìoch Làitheil
An-asgaidh 10 1 100
Starter 30 3 1,000
Pro 60 10 10,000
Enterprise Gnàthaichte Gnàthaichte Gun chrìoch
Bannan-cinn Crìoch Luaths: Thoir sùil air bannan-cinn na freagairt airson inbhe nan crìochan an-dràsta:
  • X-RateLimit-Limit: Maximum requests per window
  • X-RateLimit-Remaining: Requests remaining
  • X-RateLimit-Reset: Window reset timestamp

Na Cleachdaidhean as Fheàrr

1. Optimaisich na Brosnachaidhean agad

Sgrìobh brosnachaidhean soilleir, tuairisgeulach airson na toraidhean as fheàrr:

  • Be specific about visual elements, style, and mood
  • Include details about lighting, camera angles, and composition
  • Avoid contradictory or impossible requests

2. Làimhsich Pròiseasadh Neo-shioncronach

Tha an cruthachadh neo-shioncronach. Cuir an sàs dòigh sgrùdaidh (polling) no webhooks:

// Polling example
async function pollStatus(jobId) {
  let status = 'processing';
  while (status === 'processing') {
    await sleep(2000); // Wait 2 seconds
    const result = await checkJobStatus(jobId);
    status = result.status;
  }
  return result;
}

3. Ath-shlànachadh Mhearachdan

Cuir an sàs loidsig ath-fheuchainn le dàil eas-chruthach (exponential backoff):

async function retryWithBackoff(fn, maxRetries = 3) {
  for (let i = 0; i < maxRetries; i++) {
    try {
      return await fn();
    } catch (error) {
      if (i === maxRetries - 1) throw error;
      await sleep(Math.pow(2, i) * 1000);
    }
  }
}

4. Cum sùil air Cleachdadh Chreideasan

Cum sùil air na creideasan a chleachdas tu gus nach bi briseadh sam bith ann:

  • Check credit balance before large batch operations
  • Set up alerts for low credit thresholds
  • Implement credit-aware request queuing

Deiseil airson Tòiseachadh?

Thig còmhla ri mìltean de luchd-leasachaidh a tha a' cleachdadh Stable Diffusion API gus susbaint iongantach a chruthachadh

Faigh Iuchair API Faic na Prìsean