All pages
Powered by GitBook
1 of 7

Loading...

Loading...

Loading...

Loading...

Loading...

Loading...

Loading...

JavaScript

CGPT SDK and API Docs

QuickStart Guide

ChainGPT AI NFT Generator QuickStart Guide

This QuickStart walks you through generating AI images and minting NFTs using ChainGPT’s API and SDK — with real examples, valid parameters, and everything you need to go live fast.


Prerequisites

Before you begin, make sure you have the following in place:

  • ChainGPT API Key: Sign up on the ChainGPT platform and obtain an API key from the API dashboard. Every request must include this key in the Authorization header (as a Bearer token). Also ensure your account has sufficient credits (see Pricing & Credits below) – requests will fail if you run out of credits.

  • Node.js Environment: Install (for using the SDK). You’ll also need a package manager like npm or Yarn.

  • API Access Tool: For making raw API calls, you can use cURL (as shown in examples) or any HTTP client (Postman, etc.). All API endpoints are relative to the base URL https://api.chaingpt.org.

Note: Make sure your ChainGPT account has sufficient credits or an appropriate plan. NFT generation calls will fail if you run out of credits or if your API key is invalid.


Using the REST API (via cURL)

ChainGPT’s AI NFT Generator API allows you to generate AI images from text and optionally mint them as NFTs. Below we demonstrate the workflow using direct REST calls with cURL.

1. Generate an AI Image (Synchronous)

To generate an image from a text prompt, use the POST /nft/generate-image endpoint. This returns the image data directly in the response, suitable for quick previews or standalone image generation.

Request: Include your API key in the header and provide the prompt and generation parameters in JSON. For example:

In this request:

  • prompt – The text description of the image to generate.

  • model – The AI model to use (e.g. "velogen", "nebula_forge_xl", "VisionaryForge", or "Dale3" for DALL·E 3).

Response: On success, you’ll get a JSON response with the image data. For example:

The data field is an array of bytes representing the generated image (in this case, a JPEG). You can convert this to an image file. For instance, in Node.js you could do:

This will write the bytes to output.jpg. (If the API returns a base64 string instead, decode it accordingly.)

Model Options & Parameters: The API supports multiple models, each with different capabilities:

  • velogen – Fast generation for smaller images. Supports base resolutions up to ~768px and 1–4 steps (quick iterations).

  • nebula_forge_xl – High-quality model for larger images (up to 1024px) and more steps (up to 50 for fine detail).

  • VisionaryForge – Similar to Nebula Forge XL (up to 1024px, 50 steps), with its own style/profile.

  • Dale3 – Integration of OpenAI’s DALL·E 3 model. Fixed 1024Ă—1024 output, no custom steps or enhancements allowed. Use this for DALL·E’s unique output, but note it has a separate pricing structure (see below).

Each model has recommended resolution ranges. For example, velogen is optimal at 512–768px (can upscale to ~1920px with enhance: "2x"), whereas Nebula/VisionaryForge excel at 768–1024px (up to ~1536px with upscale). If you request a resolution beyond a model’s base capability without setting enhance, the API may automatically upscale it if possible. It’s best to explicitly use the enhance parameter if you want high resolution output.

2. Queue an NFT Image Generation (Asynchronous)

If you intend to mint the image as an NFT, it’s recommended to use the queued generation endpoint. This allows the backend to handle longer-running jobs and prepare NFT metadata. Use POST /nft/generate-nft-queue to start the generation without waiting for the image immediately.

Request: In addition to the prompt and image settings, you must provide:

  • walletAddress – The blockchain wallet address that will ultimately receive/own the NFT.

  • chainId – The identifier of the blockchain network where the NFT will be minted. (Use the Get Chains endpoint or see below for how to find supported chain IDs.)

Example cURL to queue a generation:

This request queues an image generation with the given parameters (prompt, model, etc.) on BSC Mainnet (chainId: 56). Higher values for steps (like 25 or even 50 for Nebula) can yield very detailed images, and here we used enhance: "2x" for an upscaled 1024→1536px output.

Response: The server immediately returns a job identifier:

The collectionId is a unique UUID for this generation task. The status will initially be "queued" (or "processing" shortly after) – no image is returned yet. You will use this ID to query the generation status and later to mint the NFT.

Note: If you only need an image (no NFT minting), you can skip the queue and use the direct generate-image endpoint (as in step 1). The queued endpoint is designed for NFT workflows, where you’ll track progress and eventually call minting endpoints.

3. Check Generation Progress

After queueing an NFT generation, you can poll its status using GET /nft/progress/{collectionId}. This returns the current status and (if completed) the result of the generation.

For example:

Response: If the job is still in progress, you’ll see something like:

Here, status is "processing" and progress is ~45%. (Some jobs may not return a percentage, just a status.) When the status becomes "completed", the response will include the image data:

In the above completed example, data contains the bytes of the generated image (starting with 137 80 78 71 which is the PNG file signature). You can now save or utilize this image (just as in step 1).

Often, instead of manually retrieving the raw image here, the next step is to call the minting API to get the NFT metadata. The image is stored on the backend once generation completes. For simplicity, you can proceed directly to Mint the NFT after you see a "completed" status.

Tip: You don’t have to query progress in a tight loop. Polling every few seconds is sufficient. Alternatively, you could implement a webhook/callback if the API provided one, but polling is straightforward for most use cases.

4. (Optional) Enhance a Text Prompt

If you have a short or less-detailed prompt and want to improve it before generating an image, you can use POST /nft/enhancePrompt. This endpoint uses AI to refine your prompt (making it more descriptive or creative), which can lead to better image outcomes.

For example:

Response:

The API returns an enhancedPrompt field containing a more detailed version of your input. You can then take this suggestion and use it as the prompt in your next generate-image or generate-nft-queue call. Each prompt enhancement call costs a small number of credits (0.5 credits per call).

(Using prompt enhancement is optional but recommended if you’re not getting the desired detail in the outputs. It can help maximize the quality of the image, especially for expensive models or high-step generations.)

5. Retrieve Supported Blockchains (Get Chains)

The AI NFT Generator supports minting on multiple blockchain networks. To see which chainId values you can use, call GET /nft/get-chains:

By default, this returns only mainnets. Add ?testNet=true to include test networks. A sample response:

Each entry has a chainId and name. Use these IDs in the generation and minting calls. For example, 56 for Binance Smart Chain, 1 for Ethereum, 137 for Polygon, etc. If you’re testing on a testnet (like BSC Testnet or Goerli), be sure to both use the testnet chainId and a wallet address from that test network.

6. Mint the NFT (Finalize Metadata & Minting)

Once your image is generated (and you have a collectionId from the queued generation), the final step is to mint the NFT. This involves calling POST /nft/mint-nft with the collectionId and some NFT metadata. This call will prepare the NFT’s metadata (and potentially trigger the on-chain mint, depending on the setup).

Request: Provide:

  • collectionId – The ID from the completed generation job (ensure the status was “completed” before minting).

  • name – A name/title for the NFT (e.g. "Neon Skyline City").

  • description – A description for the NFT, detailing the artwork or any info you want in the token metadata.

Example cURL:

Response: If successful, you will receive metadata about the newly created NFT. For example:

This includes the name, description you provided, and importantly an image URL (often an IPFS link to the image that was uploaded). Additional metadata like attributes could appear if relevant. The transaction field may contain a transaction hash if the system initiated an on-chain mint for you, or null if not applicable.

At this point, the NFT’s data is ready. If the service did not automatically mint the NFT on-chain, you have two options to finalize the minting:

  • Use the ChainGPT NFT contract to mint the token to the provided wallet address (you'll need on-chain interaction, see Contract ABI below).

  • Or, if transaction was returned, wait for that transaction to confirm on-chain (or fetch it via a blockchain explorer).

In most cases, you will need to perform the actual blockchain transaction yourself. The mint-nft response gives you the metadata (and the image is now pinned e.g. on IPFS). Now you or your backend can call the blockchain smart contract’s mint function to create the NFT.

7. (Optional) Get the NFT Contract ABI

If you plan to interact with the NFT smart contract directly (to manually call the mint function, or to integrate with web3 tooling), you can fetch the contract’s ABI via GET /nft/abi. This returns the ABI (Application Binary Interface) JSON of the ChainGPT NFT Mint Factory contract.

Example:

Response:

This ABI JSON can be used with a web3 library (Ethers.js, Web3.py, etc.) to invoke the contract. Typically, the NFT contract has a mint(address to, string tokenURI) function you’ll call, passing the walletAddress and a token URI (which the backend has likely already created for you, pointing to the metadata JSON). The ABI also defines events like NFTMinted that you could listen for.

Using the ABI from the API ensures you’re interacting with the correct contract and function signature. After calling mint-nft (Step 6), you would use this ABI along with the collectionId/metadata info to execute an on-chain transaction to actually mint the NFT to the user’s wallet.


Using the Node.js SDK (@chaingpt/nft)

ChainGPT provides an official JavaScript/TypeScript SDK (@chaingpt/nft on npm) to simplify integration. This SDK wraps all the above API calls into convenient functions. In this section, we’ll accomplish the same tasks using Node.js.

1. Installation and Setup

First, install the SDK into your Node.js project:

Import and initialize the SDK in your code with your API key:

Here we store the API key in an environment variable for safety (you can replace process.env.CHAINGPT_API_KEY with your key string for testing, but avoid hardcoding secrets in production). The Nft class instance nft will be used to call all NFT API methods.

2. Generate an Image using the SDK

To generate an image, use the nft.generateImage() method. This mirrors the POST /nft/generate-image endpoint.

A few notes on the above code:

  • The parameters prompt, model, steps, height, width, enhance are the same as described in the REST API section and are passed in as an object. The values here will produce a 512Ă—512 image using the velogen model with 2 refinement steps and a 1Ă— enhancement (effectively upscaled from 256px base to 512px output, since velogen’s base resolution is smaller).

  • imageResult

This method is synchronous from the caller’s perspective (it awaits the image generation to complete and returns the image). Use this for quick generation or when you need the image immediately.

Model options and parameters (as discussed earlier) apply here as well. For example, you could switch model to "nebula_forge_xl" and increase steps to 25 for a higher-quality image (just ensure to adjust height/width within that model’s range, e.g. 1024×1024, and consider using enhance: "2x" for maximum quality). The SDK will call the appropriate API and retrieve the result.

3. Get Supported Chains (Networks)

You can retrieve the list of supported blockchains via the SDK using nft.getChains(). By default, getChains() returns mainnets; pass true to include testnets.

This will fetch the same data as the /nft/get-chains API. Each call returns an object containing a chains array (accessible via .data in the SDK response). For example, chainsMainnet.data.chains might include entries like { chainId: 56, name: 'BSC Mainnet', ... }. Use these IDs for the chainId parameter in generation and minting.

4. Generate an NFT (Image + Metadata) using the SDK

To generate an image with the intent to mint it as an NFT, you have two options in the SDK:

  • Immediate generation with nft.generateNft(): This will wait for the image generation to complete and return the image data plus a collectionId. Use this if your application can afford to wait (e.g. 30-60 seconds) for the generation to finish in one go.

  • Queued generation with nft.generateNftWithQueue(): This will return immediately with a collectionId (similar to the REST generate-nft-queue), and you can then poll progress with nft.getNftProgress()

For simplicity, here’s how to use generateNft() for a synchronous flow:

This call will take some time to resolve (it internally queues the generation and waits for completion). Once it returns, you get an object result containing the image data and a collectionId. We log the collectionId for reference. At this point, the image is generated and stored, and you can proceed to mint it.

Note: We used chainId: 97 (BSC Testnet) above for testing. In production, you might use a mainnet chain like 56 for BSC or 1 for Ethereum, etc. Ensure the walletAddress is compatible with the chain.

If instead you prefer to not block execution, you could use generateNftWithQueue():

This returns immediately with the collectionId. You can then call nft.getNftProgress({ collectionId }) in intervals to check status and progress, similar to the REST polling in step 3. The usage of getNftProgress is straightforward:

It will output the status ("queued", "processing", or "completed") and progress percent if available. Once completed, you could retrieve the image (though if you plan to immediately mint, you might skip directly retrieving the raw image and just call mintNft as shown next).

5. Enhance a Prompt via SDK (Optional)

To use the prompt enhancement feature through the SDK, call nft.enhancePrompt():

This will return an object whose data.enhancedPrompt is the improved prompt text (just like the REST response). You can then use that string in generateImage or generateNft calls to potentially get better results. Each call costs ~0.5 credits.

6. Mint the NFT (using the SDK)

After generating the NFT (and obtaining a collectionId), use the SDK’s nft.mintNft() method to retrieve the minting details and finalize the NFT.

In this snippet, replace collectionId with the ID from the generation step (e.g. result.data.collectionId from generateNft() earlier). The mintNft call requires the same three metadata fields: name, description, symbol. On success, mintRes.data will contain the NFT metadata and possibly a transaction reference, similar to the REST response. You should see the image URL (likely an IPFS link) and the collectionId echoed back. If the SDK/backend initiated an on-chain mint, a transaction hash might be present in the data; if not, you’ll use the ABI to mint manually.

After this, the NFT’s metadata is on-chain or ready to be minted on-chain. If no auto-mint happened, the next step would be using a blockchain library to call the actual smart contract’s mint function, as described below.

7. Get the NFT Contract ABI (SDK)

You can fetch the NFT contract’s ABI via the SDK as well with nft.abi():

This returns the same JSON ABI that the REST call would. You can use this output in your web3 interactions. For example, with Ethers.js you might do:

Where tokenURI is the metadata URL (e.g. the IPFS link) you got from mintNft(). The exact contract address to use would be provided by ChainGPT’s documentation for each chain (or possibly returned in the mint response or available in the getChains data if a new contract is deployed per chain).

Note: The above blockchain interaction is just an illustration; the QuickStart’s scope is primarily the ChainGPT API/SDK usage. In practice, consult ChainGPT docs on whether a new contract is deployed or a shared factory contract is used across chains, and how the tokenURI is structured.


Pricing & Credit Usage

ChainGPT’s NFT Generator API uses a credit system. Each API call deducts credits from your balance, so you should understand the costs:

  • Standard image generation (ChainGPT models): Using models like velogen, nebula_forge_xl, or VisionaryForge costs 1 credit per image at base resolution. If you use enhancement ("1x" or "2x"), it costs 2 credits per image (effectively +1 credit for the upscale). For example, generating a 1024Ă—1024 image with Nebula Forge XL will cost 1 credit, and if you set enhance: "1x" (HD upscale), it will cost 2 credits.

Make sure you have enough credits for the operations you plan to run. For example, a single generateNft with Nebula (no enhance) will use 1 credit, plus a mintNft call (0 credits) – total 1 credit. The same with DALL·E 3 might use ~4.75 credits. If you plan to generate many images or use upscale frequently, ensure your credit balance is topped up accordingly.

Refer to the official pricing page for the latest credit costs and any changes to the model pricing structure.


Error Handling

Both the REST API and SDK provide error information to help you diagnose issues:

  • HTTP Status Codes: The REST API returns standard codes. A 200 OK indicates success (image or job created). 400 Bad Request means something was wrong with your request (e.g., missing required field or invalid parameter value). For instance, if you exceed a model’s resolution limits, you might get a 400 with an error message like {"error": "height and width exceed allowed resolution for model velogen"}. 401 Unauthorized means your API key is missing/invalid, or you’ve run out of credits – check that you included the correct Bearer token and have sufficient credits. 429 Too Many Requests indicates you hit a rate limit or tried to use the API with no credits (the service may also treat no-credit attempts as a form of rate limit). 500 Internal Server Error is a rare server-side issue – you can retry after a delay or contact support if it persists. The error responses typically include a JSON body with an "error"


Supported Styles

Here is a list of supported models:

3d-model

analog-film

anime

cinematic

comic-book

digital-art

enhance

fantasy-art

isometric

line-art

low-poly

neon-punk

origami

photographic

pixel-art

texture

craft-clay

Next Steps and Additional Resources

You have now generated AI-driven images and minted an NFT using ChainGPT’s API and SDK. From here, you can integrate these calls into your application’s backend or frontend. For a more in-depth understanding of each endpoint and method, refer to the official ChainGPT AI NFT Generator API Reference and SDK Reference documentation. These resources provide detailed descriptions of all parameters, more example scenarios, and information on advanced features.

For any questions or support, check out the ChainGPT community channels or contact the team as listed on the ChainGPT website. Happy building your NFT application with ChainGPT’s AI NFT Generator!

Secure Key Storage: Treat your API key like a password – store it securely (for example, in environment variables or a secrets manager), not hard-coded in your code or pushed to repositories.

steps – (Optional) Number of refinement steps. Higher values can yield more detail but take longer. Each model has a range: velogen supports 1–4 steps (default 2), nebula_forge_xl and VisionaryForge support up to 50 (default 25), while Dale3 (DALL·E 3) doesn’t use a steps parameter.
  • height and width – The image dimensions in pixels. Ensure they are within the supported range for the chosen model (see Model Options below). Common base sizes are 512 or 768 for quick generation, or 1024 if supported.

  • enhance – (Optional) Upscaling option for higher resolution. Use "1x" for 1Ă— enhancement or "2x" for 2Ă— enhancement. If omitted or set to "original", the image is generated at base resolution (no upscale). Using enhancement produces a larger image (up to the model’s max upscale) at additional credit cost.

  • symbol – A short symbol or ticker for the NFT/collection (e.g. "NEON").

  • ids - An array of ID lists, where each ID corresponds to a token minted from the collections.

  • will be an object containing the image data. Typically, the SDK returns a structure similar to the API’s JSON. In this case,
    imageResult.data.data
    is the byte array of the image (the double
    .data
    is because the SDK may wrap the response). We convert it to a Buffer and write to a file.
  • Error handling: we wrap the call in a try/catch to catch any exceptions (network issues, invalid parameters, etc.).

  • if needed. Use this if you want to handle the waiting or progress feedback in your app manually (for example, show a progress bar).
    DALL·E 3 model (Dale3):
    This third-party model has higher costs. Generating a 1024×1024 image with DALL·E 3 uses about
    4.75 credits
    (standard quality). Using HD upscale on it roughly doubles the cost to
    ~9.5 credits
    . For other resolutions (since DALL·E can only output 1024×1024 internally, the service resizes if you ask for non-1024 dimensions), the cost is about
    9.5 credits
    (standard) or
    ~14.25 credits
    with HD. In short, DALL·E 3 is significantly more expensive per image.
  • Prompt Enhancement: Each call to the /nft/enhancePrompt endpoint costs 0.5 credits (since it’s a lighter-weight operation).

  • Minting calls and others: Calling mint-nft or get-chains does not typically deduct credits (they mostly prepare data or fetch info). The main costs are for image generation and prompt enhancement.

  • message explaining what went wrong.
  • SDK Exceptions: In the Node.js SDK, errors from the API are thrown as exceptions. Specifically, they will be instances of the Errors.NftError class if they originate from a non-200 API response. You should wrap SDK calls in try/catch. For example:

    This way you can distinguish ChainGPT API errors (e.g., invalid input, no credits, etc., conveyed in err.message) from other runtime errors. The SDK’s error message will usually match the JSON error from the HTTP response.

  • Debugging Tips: Ensure that all required parameters are provided (the SDK’s TypeScript definitions can help catch missing fields). If you get a 401, double-check the API key. If an image generation is failing consistently, try the enhancePrompt to improve your prompt, or reduce the resolution/steps in case it’s hitting limits. On rate limits (429), implement a backoff/retry after the suggested time.

  • Node.js
    API Reference
    SDK Reference
    const { Errors } = require('@chaingpt/nft');
    try {
      const response = await nft.generateImage({ ... });
      // use response
    } catch (err) {
      if (err instanceof Errors.NftError) {
        console.error("ChainGPT API Error:", err.message);
      } else {
        console.error("Unexpected Error:", err);
      }
    }
    curl -X POST "https://api.chaingpt.org/nft/generate-image" \
         -H "Authorization: Bearer YOUR_API_KEY" \
         -H "Content-Type: application/json" \
         -d '{
               "prompt": "A majestic dragon under a sunset sky",
               "model": "velogen",
               "steps": 3,
               "height": 512,
               "width": 512,
               "enhance": "1x"
             }'
    {
      "data": [ 255, 216, 237, ... ]
    }
    fs.writeFileSync("output.jpg", Buffer.from(response.data));
    curl -X POST "https://api.chaingpt.org/nft/generate-nft-queue" \
         -H "Authorization: Bearer YOUR_API_KEY" \
         -H "Content-Type: application/json" \
         -d '{
               "walletAddress": "0xABC123...DEF",
               "prompt": "Futuristic city skyline at night, neon glow",
               "model": "nebula_forge_xl",
               "steps": 25,
               "height": 1024,
               "width": 1024,
               "enhance": "2x",
               "amount":1,
               "chainId": 56
             }'
    {
      "collectionId": "b8f86f05-5e8a-4f21-8c4a-xxxxxxxxxxxx",
      "status": "queued"
    }
    curl -X GET "https://api.chaingpt.org/nft/progress/b8f86f05-5e8a-4f21-8c4a-xxxxxxxxxxxx" \
         -H "Authorization: Bearer YOUR_API_KEY"
    {
      "collectionId": "b8f86f05-5e8a-4f21-8c4a-xxxxxxxxxxxx",
      "status": "processing",
      "progress": 45
    }
    {
      "statusCode":200,
       "message":"Request Successful",
       "data":{"images":["https://ipfs..../..1.png"],
       "generated":true}
    }
    curl -X POST "https://api.chaingpt.org/nft/enhancePrompt" \
         -H "Authorization: Bearer YOUR_API_KEY" \
         -H "Content-Type: application/json" \
         -d '{
               "prompt": "a futuristic city"
             }'
    {
      "enhancedPrompt": "A sprawling futuristic cityscape at night, illuminated by neon lights and flying vehicles, with towering skyscrapers and advanced technology."
    }
    # Fetch mainnet chains only
    curl -X GET "https://api.chaingpt.org/nft/get-chains?testNet=false" \
         -H "Authorization: Bearer YOUR_API_KEY"
    {
      "chains": [
        { "chainId": 56, "name": "BSC Mainnet", "network": "mainnet" },
        { "chainId": 1,  "name": "Ethereum",   "network": "mainnet" },
        { "chainId": 97, "name": "BSC Testnet","network": "testnet" },
        ...
      ]
    }
    curl -X POST "https://api.chaingpt.org/nft/mint-nft" \
         -H "Authorization: Bearer YOUR_API_KEY" \
         -H "Content-Type: application/json" \
         -d '{
               "collectionId": "b8f86f05-5e8a-4f21-8c4a-xxxxxxxxxxxx",
               "name": "Neon Skyline City",
               "description": "A futuristic city skyline at night, generated by AI.",
               "symbol": "NEON",
               "ids":[1,.....n]
             }'
    {
      "name": "Neon Skyline City",
      "description": "A futuristic city skyline at night, generated by AI.",
      "image": "ipfs://Qm...abcd",
      "attributes": [ /* ... */ ],
      "collectionId": "b8f86f05-5e8a-4f21-8c4a-xxxxxxxxxxxx",
      "transaction": null
    }
    curl -X GET "https://api.chaingpt.org/nft/abi" \
         -H "Authorization: Bearer YOUR_API_KEY"
    {
      "abi": [
        {
          "type": "function",
          "name": "mint",
          "inputs": [
            { "name": "to", "type": "address" },
            { "name": "tokenURI", "type": "string" }
          ],
          "outputs": [ ... ]
        },
        {
          "type": "event",
          "name": "NFTMinted",
          "inputs": [ ... ]
        }
        // ... other functions and events ...
      ]
    }
    npm install --save @chaingpt/nft
    # or
    yarn add @chaingpt/nft
    const { Nft } = require('@chaingpt/nft');  // import the SDK class
    // import * as fs from 'fs';               // Node.js file system, if needed for saving files
    
    const nft = new Nft({
      apiKey: process.env.CHAINGPT_API_KEY  // your ChainGPT API Key
    });
    const fs = require('fs');
    
    async function quickGenerateImage() {
      try {
        const imageResult = await nft.generateImage({
          prompt: "A majestic dragon under a sunset sky",
          model: "velogen",
          steps: 2,
          height: 512,
          width: 512,
          enhance: "1x"
        });
        // The response contains the image data buffer.
        // Save it to a file:
        fs.writeFileSync("generated-image.jpg", Buffer.from(imageResult.data.data));
        console.log("Image saved to generated-image.jpg");
      } catch (error) {
        console.error("Image generation failed:", error);
      }
    }
    
    quickGenerateImage();
    async function listChains() {
      const chainsMainnet = await nft.getChains();        // same as getChains(false)
      const chainsIncludingTest = await nft.getChains(true);
      console.log("Mainnet chains:", chainsMainnet.data);
      console.log("All chains (with testnets):", chainsIncludingTest.data);
    }
    async function generateAndPrepareNFT() {
      try {
        const result = await nft.generateNft({
          prompt: "Futuristic city skyline at night, neon glow",
          model: "nebula_forge_xl",
          steps: 25,
          height: 1024,
          width: 1024,
          enhance: "2x",
          walletAddress: "0xABC123...DEF",
          chainId: 97,  // BSC Testnet for example
          amount:1
        });
        console.log("NFT generation completed. Collection ID:", result.data.collectionId);
        // The image data is also available in result.data (similar to generateImage).
      } catch (error) {
        console.error("NFT generation failed:", error);
      }
    }
    const queueResult = await nft.generateNftWithQueue({ ...params });
    console.log("Queued Collection ID:", queueResult.data.collectionId);
    const progressRes = await nft.getNftProgress({ collectionId: queueResult.data.collectionId });
    console.log(progressRes.data);
    async function enhanceMyPrompt() {
      const res = await nft.enhancePrompt({ prompt: "a futuristic city" });
      console.log("Enhanced prompt:", res.data.enhancedPrompt);
    }
    async function mintGeneratedNFT(collectionId) {
      try {
        const mintRes = await nft.mintNft({
          collectionId: collectionId,
          name: "Neon Skyline City",
          description: "A futuristic city skyline at night, generated by AI.",
          symbol: "NEON",
          ids:[1,....,n]
        });
        console.log("Mint response:", mintRes.data);
      } catch (error) {
        console.error("Minting failed:", error);
      }
    }
    async function getContractABI() {
      const abiRes = await nft.abi();
      console.log("Contract ABI:", abiRes.data);
    }
    const contractAddress = "<ChainGPT_NFT_Contract_Address_For_Selected_Chain>";
    const abi = abiRes.data.abi;
    const provider = new ethers.providers.JsonRpcProvider(<RPC_URL>);
    const signer = new ethers.Wallet(<PRIVATE_KEY>, provider);
    const nftContract = new ethers.Contract(contractAddress, abi, signer);
    await nftContract.mint(walletAddress, tokenURI);

    AI NFT Generator (API & SDK)

    ChainGPT AI NFT Generator (API & SDK) Overview

    ChainGPT’s AI NFT Generator is a full-stack API and SDK for creating, minting, and managing NFTs through AI. It’s the first solution to combine AI-driven image generation with on-chain NFT minting in one platform, so developers can go from an idea to a blockchain asset seamlessly. With a single integration, you can generate unique images from text prompts, convert them into NFT metadata, and mint them on multiple blockchains – all without needing separate AI models or smart contract code​. This empowers developers, product teams, and Web3 projects to launch NFT features faster, using ChainGPT’s infrastructure to handle the heavy lifting.


    Key Use Cases

    • Single NFT Generation: Create one-off AI-generated NFTs on demand. For example, users in a game or app can input a prompt to instantly get a custom NFT avatar or digital collectible. The API returns the generated image and token data, ready to mint or display.

    • Full Collection Creation: Generate entire NFT collections (up to 10,000 images) in one go​. The AI can produce large sets of art with variation, which you can mint as a series (e.g. generative profile picture collections). This dramatically speeds up launching an NFT project – what used to take weeks of manual design can happen in under a minute.

    • Integrated Minting: Every image comes with mint-ready metadata. You can directly mint the AI-generated art as an NFT on the chosen blockchain via the API/SDK, without writing custom smart contracts. The service handles token creation, storage of the image/metadata, and linking it all on-chain.


    How It Works

    High-level workflow: the AI NFT Generator handles everything from prompt to minting.

    The process starts with a text prompt provided by the developer or user, describing the desired artwork. The AI model then generates an image based on this prompt (using advanced text-to-image algorithms). Next, the system creates an NFT metadata JSON for the image – including details like title, description, and any traits, plus a link to the image file. With one API call, the platform mints a new NFT token on the specified blockchain, attaching the generated image and metadata to it. Finally, your NFT collection can be added to your wallet and used as you wish! All these steps are orchestrated behind a single API/SDK interface, so you don’t need to manage them separately.


    Integration Options: API vs SDK

    ChainGPT offers both a RESTful API and a client SDK, so you can choose the integration path that fits your stack:

    • REST API: Integrate via HTTP endpoints accessible in any language or platform. This option is ideal if you want direct control or are working in a backend environment outside of Node.js. You send requests with the prompt, parameters, and target chain, and receive the generated image/metadata or transaction details in JSON responses. (If you only need image generation without minting, a lightweight text-to-image API endpoint is available as well.) See the API Reference for full endpoint details and examples.

    • JavaScript/TypeScript SDK: Use ChainGPT’s official SDK package for Node.js projects. The SDK provides convenient methods that wrap the API calls – for example, generateImage() or generateNft() – abstracting away raw HTTP calls and handling tasks like file I/O. It’s well-suited for frontend web apps, Node backends, or scripts, and includes TypeScript type definitions for safer development. The SDK simplifies common workflows (such as queuing batch jobs or tracking generation progress) with one-line function calls. Refer to the SDK Reference for installation and code snippets.

    (Both the API and SDK require an API key for authentication. You can obtain this key from the ChainGPT – see “Get Started” below.)


    Supported Blockchains

    One of the AI NFT Generator’s strengths is broad multichain support. Out of the box, you can mint NFTs on a wide range of networks without any custom setup. Supported chains include:

    • Ethereum – Mainnet and testnets

    • Binance Chain (BNB) – and opBNB layer 2

    • Polygon (Ethereum sidechain)

    • Arbitrum One and other L2s

    In total, 25+ blockchain networks are integrated. The API/SDK uses a simple chainId parameter to select the target network, so switching the mint destination (or offering a choice to your users) is straightforward. ChainGPT handles the low-level differences between chains, providing a unified NFT minting experience across ecosystems.


    Unique Capabilities

    ChainGPT’s AI NFT Generator comes with several powerful features that distinguish it from basic image APIs:

    • Prompt Enhancement & Suggestions: To help improve results, the platform includes an “Enhance Prompt” option that refines your input text for a better image output. There’s also a “Surprise Me” feature that suggests random creative prompts, which can inspire users or generate diverse outputs without extra input. These tools lower the barrier for non-artists to get high-quality NFTs.

    • Batch Queueing for Collections: When generating large collections, you can use the queue system to process images asynchronously. Rather than waiting on one NFT at a time, the SDK allows queuing up generation tasks (e.g. generateNftWithQueue() in the SDK) so you can request hundreds or thousands of images in parallel​file-leehq5gwmzjy2dqf8wha2q. The API provides methods to check generation progress and retrieve results when ready, enabling scalable NFT creation workflows.


    Developer-Friendly Design

    The AI NFT Generator API & SDK are built with developers in mind, focusing on quick integration and robust performance:

    • Fast & Efficient: Generation and minting are optimized for low latency. In typical cases, an NFT (image + on-chain mint) can be produced in 30–60 seconds. Even bulk operations use parallel processing and queueing to finish quickly. This speed lets you integrate on-demand NFT creation in real time applications (like letting a user design an NFT and mint it during a sign-up flow) without long waits.

    • No AI/ML Expertise Needed: You don’t have to train models or manage machine learning pipelines. ChainGPT’s models are pre-trained and continuously improved by the team, so you simply leverage them via API. There’s no need for you to gather datasets, run GPU servers, or tweak neural network parameters – the service delivers great results out-of-the-box.

    • Customizable Outputs: While the default settings work for most cases, developers can fine-tune the generation process through parameters. You can adjust the diffusion steps


    Next Steps

    • Quickstart Guide: Follow the step-by-step Quickstart to create your first AI-generated NFT using the API/SDK. This guide covers setting up your API key, making a test generation call, and minting a sample NFT (ideal for newcomers).

    • API Reference: Refer to the API reference for a complete list of endpoints, parameters, and response schemas. Each feature (image generation, minting, etc.) is documented with example requests and responses to help you build correctly.

    • SDK Reference: Check out the SDK documentation for usage of the JavaScript/TypeScript library. It includes code snippets for all major functions (generate image, mint NFT, queue jobs, etc.) and best practices for integrating the SDK into your project.

    • Pricing & Credits: ChainGPT’s AI NFT Generator API uses a simple and transparent credit system. Each API request consumes credits based on the model selected, generation options, and image resolution. Learn more about our pricing.

    Get Started: To start building with ChainGPT’s AI NFT Generator, sign up for an API key via the ChainGPT web app and review the Quickstart Guide. With just a few lines of code, you can integrate AI-powered NFT creation and minting into your product today. Enjoy exploring the possibilities and happy coding!

    Metadata Control: Developers retain control over NFT metadata. By default the system generates standard metadata (e.g. name, description, traits) for each NFT, but you can override or post-edit attributes as needed. This is useful for injecting project-specific traits or ensuring metadata consistency across a collection.

  • Multi-Chain Deployment: Easily deploy NFTs across multiple blockchains from the same API. The AI NFT Generator supports BNB Chain (BSC) and opBNB, Ethereum, Polygon, Arbitrum One, Avalanche, Cronos, Tron, Base, and many more – over 25 networks in total​. You can specify a target chain ID for each mint, enabling cross-chain NFT support without additional tools.

  • Avalanche, Cronos, Hedera, Immutable X

  • Tron, Mantle, CoreDAO, Linea

  • Base, Scroll, Skale, 5ire, and more...

  • Flexible Image Output Settings: You have control over the size and aspect ratio of generated images. The generator supports multiple aspect ratios (e.g. 1:1 square, 3:2 rectangle, etc.) and custom dimensions up to high resolutions​. It also offers built-in upscaling options (1Ă— or 2Ă—) to enhance image resolution after generation. This flexibility means you can tailor the output to your platform’s requirements (thumbnail vs. high-res print, etc.).
  • Multiple AI Art Models: The service provides a selection of AI models/styles to generate art in different aesthetics. For example, you might choose a Realistic model for photorealistic art, an Anime model for cartoon-style NFTs, a 3D Render model for game assets, or others like Drawing or Pixel Art. By selecting the model best suited to your use case, you can maintain a consistent style across your NFTs or offer users a choice of artistic styles.

  • Advanced Collection Generation: Beyond single images, the AI NFT Generator can automate trait assignment and rarity for generative collections. You can supply base assets or let the AI create variations, and the system will combine traits to produce unique NFTs with rarity distribution​. This is particularly useful for profile-picture (PFP) projects that involve layering attributes (hats, glasses, backgrounds, etc.) across thousands of NFTs. The heavy lifting of randomizing traits and ensuring each NFT is one-of-a-kind is handled for you.

  • (to control image refinement), toggle
    enhancements
    , select different generator
    models
    , and set image dimensions. The output NFTs can thus be customized to fit your application’s style and quality requirements.
  • Straightforward Onboarding: Getting started is simple. Just obtain an API key from ChainGPT’s developer portal and you can begin calling the API or SDK immediately (no complex setup). The SDK can be installed with a single npm/yarn command and comes with clear documentation. Both the REST API and SDK use an intuitive request structure. For example, to generate an NFT you provide the prompt, choose a model, and specify a wallet address & chain – the response returns the image data or a mint transaction. Detailed guides and code examples are available in the docs to accelerate your integration.

  • API Reference
    SDK Reference
    developer dashboard
    QuickStart Guide
    API Reference
    SDK Reference
    Pricing & Credits

    Pricing & Credits

    Pricing & Credits – ChainGPT AI NFT Generator

    ChainGPT’s AI NFT Generator (API & SDK) uses a credit-based pricing model for all image generation and utilities. This means every request consumes ChainGPT Credits (CGPTc), where 1 credit = $0.01 USD. The pricing is consistent across the API, SDK, and web app – there is no markup for API usage. Developers only pay per use (pay-as-you-go), making costs transparent and easy to track.

    Note: Basic free daily usage is available on the platform for single-image generation, but programmatic use beyond those limits will consume credits. If you want to try out our models & application for free, visit : .


    Image Generation Pricing

    ChainGPT’s NFT Generator offers three AI models for image creation, each suited to different needs:

    • VeloGen – a fast, efficient model for quick drafts.

    • NebulaForge XL – a high-fidelity model (XL) for premium, detailed outputs.

    • VisionaryForge – a creative model for imaginative, high-quality visuals.

    Despite their differences in speed and quality, all in-house models cost the same base amount in credits per image. You can customize each generation by adjusting the number of diffusion steps (which refines quality) and the output resolution, without changing the base credit cost. The table below summarizes pricing per image for each model, including optional enhancements:

    Model
    Credits Per Image

    💡 Tip: You can significantly enhance image quality or double the resolution by applying the Upscale (1x or 2x) utility feature—see details below.

    Key Points:

    • Base Generation Cost: Generating an image with any of the three models costs 1 credit per image by default. This covers any prompt and any supported base resolution, regardless of how many steps are used. (Using more steps yields higher quality but may take longer; it does not increase the credit cost.)

    • Upscaling Cost: If you request HD/Enhanced output, the system will automatically apply the upscaler. This roughly doubles the cost – +1 credit for a single enhancement (so 2 credits total). All models support upscaling; for instance, VeloGen can upscale a 512px image to ~1920px. Upscaling twice (for even larger images) adds another credit (total 3 credits), though one pass is usually sufficient.

    • Model Selection: Using VeloGen


    Utilities Pricing

    In addition to image generation, the ChainGPT NFT API provides several utility features to enhance your results or enforce content guidelines. Below is a breakdown of these tools, including which are free and which consume credits:

    Utility Tool
    Credit Cost
    Description & Usage

    Note: The prompt enhancer and upscaler are optional tools to help you get better results with fewer tries. They incur small credit fees as noted. The NSFW safety filter is built-in for compliance and does not charge credits.


    Model Comparison

    All three models share the same base credit cost (1 credit per image). Select a model based on your project’s balance of speed and quality.

    Model
    Best For
    Pros âś…
    Cons ⚠️

    Credit Purchase Options

    ChainGPT Credits (CGPTc) can be purchased directly through the ChainGPT dashboard. Credits never expire, and you can buy them on a one-time or recurring basis to suit your integration’s needs. Key points about purchasing credits:

    • Credit Bundles: Credits are available in flexible amounts. For example, 1,000 credits cost $10 USD (since 1 credit = $0.01) – you can scale up as needed (e.g. 10,000 credits = $100) or purchase smaller/larger packs in the app. There is no minimum usage fee; you only pay for the credits you need, and you can top-up anytime. (For enterprise or high-volume needs, larger bulk packages are available.)

    • Payment Methods: You can pay via credit/debit card or cryptocurrency. Supported crypto includes stablecoins like USDT/USDC and popular coins (e.g. ETH, BNB, TRX). Additionally, you may purchase credits using $CGPT (ChainGPT’s native token). All purchases are processed through the ChainGPT Crypto AI Hub interface for convenience.

    • Discounts for $CGPT or Subscriptions:

    All credit transactions and balances can be managed via your ChainGPT account dashboard. Credits are deducted in real-time as you make API/SDK calls, and you can monitor usage in the dashboard to plan when to top-up.


    Best Practices & Tips

    Follow these recommendations to efficiently use ChainGPT’s NFT Generator and maximize your credits:

    1. Optimize Prompts with Enhancement: Before generating images repeatedly, use the Prompt Enhancement tool (1 credit). It helps create detailed, effective prompts on your first try, reducing unnecessary spending.

    2. Prototype Quickly with VeloGen: Start initial tests and bulk generations with VeloGen (1 credit per image). It's fast and cost-effective, allowing quick iteration. Once satisfied, switch to NebulaForge XL or VisionaryForge for high-quality final outputs.

    3. Use Image Upscaling Strategically: Only use upscaling (enhancement) when higher resolution or improved clarity is essential. For drafts or previews, skip enhancement to save credits. Apply 1Ă— Upscale for improved quality or 2Ă— Upscale for exceptional detail and resolution.

    4. Adhere to Content Guidelines: Ensure prompts follow content guidelines to avoid blocked generations. Non-compliant prompts may still consume credits without producing results. Use clear, appropriate, family-friendly prompts.

    5. Track Usage Regularly: Monitor your credit usage via the ChainGPT dashboard. Regular tracking helps you manage credits effectively and anticipate future needs. For consistent usage, set up automatic monthly top-ups to benefit from a 15% discount.

    6. Validate with Samples Before Bulk Generation: When creating large NFT collections, always generate a small sample batch first. Validate prompt effectiveness and style consistency before committing credits to large-scale generation, ensuring your final batch meets your expectations.

    By applying these best practices, you’ll achieve optimal results and predictable costs while making the most of ChainGPT’s powerful NFT generation tools.

    is most
    cost-efficient
    for rapid prototyping or bulk previews – it generates images extremely fast with fewer diffusion steps.
    NebulaForge XL
    and
    VisionaryForge
    , on the other hand, produce more
    premium-quality
    images with finer detail (supporting up to 50 steps of refinement). They are ideal for final renders or when image fidelity is paramount.
    All three models cost 1 credit per base image
    , so you can choose the model based on your quality/speed needs without worrying about price differences.
    (Third-party models (e.g. OpenAI’s DALL·E) are also available for compatibility, but they have a separate pricing structure and are not the focus here.)

    isCharacterPreserve

    +5 credits per prompt

    An additional 5 credits will be deducted when using isCharacterPreserve, since this option requires extra processing to maintain character consistency.

    If you choose to pay with
    $CGPT tokens
    or
    if you enable an
    automatic monthly credit top-up
    subscription, you receive a
    15% credit bonus/discount
    on those purchases. This means your money goes further (for example, a $100 purchase via $CGPT yields 11,500 credits instead of 10,000). This incentive is designed to reward ecosystem users and those who plan for recurring usage.
  • Monthly Plans: For organizations or power-users, you can set up a monthly credits plan (auto-purchase). This ensures your account is refilled every month with a set number of credits, so your integration never runs out. The 15% discount applies here as well. (Alternatively, ChainGPT’s Freemium membership – achieved by staking CGPT tokens – provides a monthly allotment of credits, see Membership docs for details.)

  • VeloGen

    1 Credit

    NebulaForge XL

    1 Credit

    VisionaryForge

    1 Credit

    Prompt Enhancement

    +0.5 credits per prompt

    Enhance Prompt – Uses an AI language model to refine or expand your text prompt before image generation. This optional step can make prompts more descriptive or creative. It costs a half-credit per use.

    1x Image Upscaling

    +1 credit per upscale

    HD Enhancement – Improves image resolution and quality using a super-resolution model (R-ESRGAN). If requested as part of generation, this is counted in the image’s credit cost (as detailed above).

    2x Image Upscaling

    +2 credits per upscale

    HD Enhancement – Improves image resolution and quality using a super-resolution model (R-ESRGAN). If requested as part of generation, this is counted in the image’s credit cost (as detailed above).

    NSFW Detection

    Free (0 credits)

    VeloGen

    Good quality images, Rapid prototyping, quick previews, high-volume generation

    - Fastest generation- Cost-efficient for bulk tasks- Good results even at lower steps

    - Limited detail compared to other models- Best results at lower resolutions (512–1024px)

    NebulaForge XL

    Premium-quality NFT images, detailed artwork, final production

    - Highest image detail & fidelity- Supports large resolutions (up to 1536px with upscale)- Ideal for production-level quality

    - Slower than VeloGen (especially at high step counts)- Higher steps (26–50) slightly increase cost (+0.25 credits)

    VisionaryForge

    Premium-quality NFT images, artistic visuals, final production

    - Similar premium quality to NebulaForge XL- Excellent fine detail and color accuracy- Supports high-resolution outputs (up to 1536px)

    https://NFT.ChainGPT.org

    Content Filter – Every image generation is automatically screened for NSFW or disallowed content using a Vision-Transformer classifier. This ensures that NSFW materials are blocked and not generated. The NSFW filter does not consume credits. (However, disallowed prompts or outputs will be filtered out, so ensure your prompts comply with content guidelines to avoid wasted requests.)

    - Slower generation times similar to NebulaForge XL- Higher steps (26–50) slightly increase cost (+0.25 credits)

    Python

    CGPT SDK Docs Python

    ChainGPT AI NFT Generator SDK Documentation

    The ChainGPT AI NFT Generator SDK provides a comprehensive suite of tools to create, manage, and prepare NFTs for minting. This includes enhancing prompts, generating images (synchronously and asynchronously), tracking generation progress, retrieving minting metadata, and querying supported blockchains and contract ABIs.

    Table of Contents

    1. Installation

    2. Quick Start

    3. SDK Initialization

    4. NFT Service Overview


    Installation

    Install the ChainGPT SDK via pip:

    Or add to your requirements.txt:

    For development with environment variables:


    Quick Start

    Here's a minimal example to get you started:


    SDK Initialization

    Basic Initialization

    Required Imports


    NFT Service Overview

    Access the NFT service through the client:

    The NFT service provides seven main methods:

    • enhance_prompt(): Improve prompts for better image generation

    • generate_image(): Create images synchronously (fast preview)

    • generate_nft_queue(): Queue asynchronous NFT generation (high quality)

    • get_progress(): Track queued generation progress


    NFT Service Methods

    enhance_prompt()

    Enhances or refines a text prompt for better image generation results.

    Method Signature:

    Parameters:

    Parameter
    Type
    Required
    Description

    Request Model (EnhancePromptRequestModel):

    Field
    Type
    Required
    Description

    Response Model (EnhancePromptResponseModel):

    Field
    Type
    Description

    Example:


    generate_image()

    Generates an image synchronously based on the given prompt and parameters. Best for quick previews and testing.

    Method Signature:

    Parameters:

    Parameter
    Type
    Required
    Description

    Request Model (GenerateImageRequestModel):

    Field
    Type
    Required
    Default
    Description

    Response Model (GenerateImageResponseModel):

    Field
    Type
    Description

    Image-to-Image Generation:

    Example:

    Image-to-Image Generation:

    Using Traits:


    generate_nft_queue()

    Initiates an asynchronous NFT image generation job. Use this for high-quality images or when you don't need immediate results.

    Method Signature:

    Parameters:

    Parameter
    Type
    Required
    Description

    Request Model (GenerateNFTQueueRequestModel):

    Field
    Type
    Required
    Description

    Response Model (GenerateNFTQueueResponseModel):

    Field
    Type
    Description

    Example:


    get_progress()

    Checks the status and progress of a queued NFT generation job.

    Method Signature:

    Parameters:

    Parameter
    Type
    Required
    Description

    Response Model (NFTProgressResponseModel):

    Field
    Type
    Description

    Example:


    mint_nft_metadata()

    Generates the metadata required for minting NFTs on a blockchain. Call this after NFT generation is complete.

    Method Signature:

    Parameters:

    Parameter
    Type
    Required
    Description

    Request Model (MintNFTRequestModel):

    Field
    Type
    Required
    Description

    Response Model (MintNFTResponseModel):

    Field
    Type
    Description

    Example:


    get_chains()

    Retrieves the list of supported blockchain networks for NFT operations.

    Method Signature:

    Parameters:

    Parameter
    Type
    Required
    Default
    Description

    Response Model (GetChainsResponseModel):

    Field
    Type
    Description

    Chain Info Model (ChainInfoModel):

    Field
    Type
    Description

    Example:


    get_abi()

    Provides the ABI (Application Binary Interface) of the ChainGPT NFT smart contract for direct blockchain interaction.

    Method Signature:

    Parameters: None

    Response Model (ContractABIResponseModel):

    Field
    Type
    Description

    Example:


    Data Models & Types

    TraitModel

    Defines NFT traits/attributes for generation:

    Error Models

    All methods can raise the following exceptions:


    Enums Reference

    NFTImageModel

    Available AI models for image generation:

    Model
    Value
    Description
    Best For

    ImageEnhanceOption

    Image enhancement levels:

    Option
    Value
    Description

    Error Handling

    Basic Error Handling

    Specific Error Scenarios


    Complete Example

    Here's a comprehensive example showing the full NFT creation workflow:


    Best Practices

    1. Resource Management

    Always close the client when done:

    2. Error Handling

    Handle specific errors appropriately:

    3. Progress Tracking

    Use reasonable polling intervals:

    4. Model Selection

    Choose the right model for your use case:

    5. Prompt Engineering

    Create effective prompts:


    New Features

    Image-to-Image Generation

    The NFT service now supports image-to-image generation, allowing you to create variations based on reference images:

    Character Preservation

    When using image-to-image generation, you can preserve character features from the reference image:

    Enhanced Traits System

    The traits system has been enhanced with better support for NFT collections:

    Updated Chain Support

    The chain information now includes more detailed network information:

    Improved Response Structures

    All API responses now follow a consistent structure with proper error handling:

    This ensures better error handling and consistent data access patterns across all NFT service methods.

    NFT Service Methods
    • enhance_prompt()

    • generate_image()

    • generate_nft_queue()

    • get_progress()

    • mint_nft_metadata()

    • get_chains()

    • get_abi()

  • Data Models & Types

  • Enums Reference

  • Error Handling

  • Complete Example

  • Best Practices

  • New Features

  • mint_nft_metadata(): Generate metadata for blockchain minting

  • get_chains(): List supported blockchain networks

  • get_abi(): Get smart contract ABI

  • int

    Yes

    -

    Image height in pixels

    width

    int

    Yes

    -

    Image width in pixels

    steps

    int

    No

    Model default

    Number of refinement passes for image generation. Higher values can yield more detailed images at the cost of longer generation time. Each model supports a range: for example, velogen supports 1–4 steps (default ~2), while NebulaForge XL and VisionaryForge support up to 50 (default ~25). If not provided, a model-specific default is used.

    enhance

    ImageEnhanceOption

    No

    ORIGINAL

    Image enhancement level

    style

    str

    No

    None

    Artistic style (e.g., "fantasy_art", "cyberpunk")

    traits

    List[TraitModel]

    No

    None

    List of traits to apply

    image

    HttpUrl

    No

    None

    Reference image URL for image-to-image generation

    isCharacterPreserve

    bool

    No

    False

    Preserve character features from reference image

    height

    int

    Yes

    Image height in pixels

    width

    int

    Yes

    Image width in pixels

    chainId

    int

    Yes

    Blockchain network ID (see get_chains())

    amount

    int

    Yes

    Number of NFTs to generate in this batch

    steps

    int

    No

    Generation steps

    enhance

    ImageEnhanceOption

    No

    Enhancement level

    style

    str

    No

    Artistic style

    traits

    List[TraitModel]

    No

    List of traits

    image

    HttpUrl

    No

    Reference image URL for image-to-image generation

    isCharacterPreserve

    bool

    No

    Preserve character features from reference image

    data.progress

    int

    Progress percentage (only when processing)

    symbol

    str

    Yes

    Symbol for the NFT collection

    ids

    List[int]

    Yes

    List of NFT IDs to mint (e.g., [1] for single NFT)

    data.name

    str

    NFT name

    data.description

    str

    NFT description

    data.image

    str

    IPFS URL for the NFT image

    data.attributes

    List[Dict]

    NFT attributes/traits

    data.collectionId

    str

    Collection ID

    data.transaction

    Any

    Transaction details (if applicable)

    data.__v

    int

    MongoDB version field

    data.createdAt

    str

    Creation timestamp

    data.updatedAt

    str

    Last update timestamp

    data.__v

    int

    MongoDB version field

    data.createdAt

    str

    Creation timestamp

    data.updatedAt

    str

    Last update timestamp

    DALE3

    "Dale3"

    Alternative model

    Experimental

    request_data

    EnhancePromptRequestModel

    Yes

    Request containing the prompt to enhance

    prompt

    str

    Yes

    The text prompt you want to enhance

    statusCode

    int

    HTTP status code (200 for success)

    message

    str

    Response message

    data.enhancedPrompt

    str

    The enhanced version of your prompt

    request_data

    GenerateImageRequestModel

    Yes

    Image generation parameters

    prompt

    str

    Yes

    -

    Text prompt for image generation

    model

    NFTImageModel

    Yes

    -

    AI model to use (see Enums)

    data.type

    str

    Data type (always "Buffer")

    data.data

    List[int]

    Raw image bytes as integer array

    request_data

    GenerateNFTQueueRequestModel

    Yes

    NFT generation parameters

    walletAddress

    str

    Yes

    Blockchain wallet address for the NFT

    prompt

    str

    Yes

    Text prompt for image generation

    model

    NFTImageModel

    Yes

    statusCode

    int

    HTTP status code (201 = successfully queued)

    message

    str

    Response message

    data.collectionId

    str

    Unique ID for tracking this generation job

    collection_id

    str

    Yes

    Collection ID from generate_nft_queue() response

    statusCode

    int

    HTTP status code

    message

    str

    Response message

    data.generated

    bool

    True if generation is complete

    data.images

    List[str]

    IPFS URLs (only when generated=True)

    request_data

    MintNFTRequestModel

    Yes

    Metadata generation parameters

    collectionId

    str

    Yes

    ID of completed NFT generation job

    name

    str

    Yes

    Name of the NFT

    description

    str

    Yes

    statusCode

    int

    HTTP status code

    message

    str

    Response message

    data._id

    str

    MongoDB document ID

    data._id

    str

    MongoDB document ID

    test_net

    bool

    No

    None

    True for testnets, False for mainnets, None for all

    statusCode

    int

    HTTP status code

    message

    str

    Response message

    data.chains

    List[ChainInfoModel]

    List of supported chains

    chainId

    int

    Numerical chain ID

    chainName

    str

    Chain name (e.g., "Ethereum Mainnet")

    network

    str

    Network type ("mainnet", "testnet")

    networkType

    str

    Additional network classification

    statusCode

    int

    HTTP status code

    message

    str

    Response message

    data

    List[Dict]

    Contract ABI as JSON objects

    VELOGEN

    "velogen"

    Fast generation

    Quick previews, testing

    NEBULA_FORGE_XL

    "nebula_forge_xl"

    High quality

    Final NFTs, detailed art

    VISIONARY_FORGE

    "VisionaryForge"

    Balanced

    ORIGINAL

    "original"

    No enhancement

    ENHANCE_1X

    "1x"

    1x enhancement

    ENHANCE_2X

    "2x"

    2x enhancement

    height

    AI model to use

    Description of the NFT

    General purpose

    pip install chaingpt
    chaingpt>=1.1.4
    pip install python-dotenv  # Optional for .env file support
    import asyncio
    from chaingpt.client import ChainGPTClient
    from chaingpt.models import GenerateImageRequestModel, NFTImageModel
    
    async def quick_example():
        client = ChainGPTClient(api_key="YOUR_API_KEY")
        
        # Generate an image synchronously
        request = GenerateImageRequestModel(
            prompt="a dragon in space",
            model=NFTImageModel.VELOGEN,
            height=512,
            width=512
        )
        
        response = await client.nft.generate_image(request)
        
        # Save the image
        with open("dragon.jpg", "wb") as f:
            f.write(bytes(response.data.data))
        
        await client.close()
    
    if __name__ == "__main__":
        asyncio.run(quick_example())
    import asyncio
    from chaingpt.client import ChainGPTClient
    from chaingpt.exceptions import ChainGPTError
    
    # Basic initialization
    client = ChainGPTClient(api_key="YOUR_API_KEY")
    
    # With environment variable
    import os
    API_KEY = os.getenv("CHAINGPT_API_KEY")
    client = ChainGPTClient(api_key=API_KEY)
    from chaingpt.client import ChainGPTClient
    from chaingpt.models import (
        EnhancePromptRequestModel,
        GenerateImageRequestModel,
        GenerateNFTQueueRequestModel,
        MintNFTRequestModel,
        TraitModel,
        TraitValueItemModel,
        NFTImageModel,
        ImageEnhanceOption
    )
    from chaingpt.exceptions import ChainGPTError, APIError
    nft_service = client.nft
    async def enhance_prompt(self, request_data: EnhancePromptRequestModel) -> EnhancePromptResponseModel
    async def enhance_example():
        enhance_request = EnhancePromptRequestModel(prompt="a dragon in space")
        response = await client.nft.enhance_prompt(enhance_request)
        
        if response.statusCode == 200:
            print(f"Original: a dragon in space")
            print(f"Enhanced: {response.data.enhancedPrompt}")
            # Output might be: "A majestic dragon soaring through the cosmic void, 
            # surrounded by stars and nebulae, highly detailed, fantasy art"
    async def generate_image(self, request_data: GenerateImageRequestModel) -> GenerateImageResponseModel
    from pydantic import HttpUrl
    
    # Generate image based on a reference image
    request = GenerateImageRequestModel(
        prompt="a dragon in space",
        model=NFTImageModel.VELOGEN,
        height=512,
        width=512,
        image=HttpUrl("https://example.com/reference-image.jpg"),
        isCharacterPreserve=True  # Preserve character features from reference
    )
    
    response = await client.nft.generate_image(request)
    async def generate_image_example():
        request = GenerateImageRequestModel(
            prompt="a majestic cyberpunk dragon",
            model=NFTImageModel.VELOGEN,  # Fast model for sync generation
            height=512,
            width=512,
            steps=3,
            enhance=ImageEnhanceOption.ENHANCE_1X,
            style="cyberpunk"
        )
        
        response = await client.nft.generate_image(request)
        
        # Save the image
        image_bytes = bytes(response.data.data)
        with open("generated_image.png", "wb") as f:
            f.write(image_bytes)
        
        print(f"Image generated: {len(image_bytes)} bytes")
    from pydantic import HttpUrl
    
    # Generate image based on a reference image
    request = GenerateImageRequestModel(
        prompt="a dragon in space",
        model=NFTImageModel.VELOGEN,
        height=512,
        width=512,
        image=HttpUrl("https://example.com/reference-image.jpg"),
        isCharacterPreserve=True  # Preserve character features
    )
    
    response = await client.nft.generate_image(request)
    from chaingpt.models import TraitModel, TraitValueItemModel
    
    traits = [
        TraitModel(
            trait_type="Background",
            value=[
                TraitValueItemModel(value="night_sky", ratio=70),
                TraitValueItemModel(value="lava_pit", ratio=30)
            ]
        ),
        TraitModel(
            trait_type="Color",
            value=[
                TraitValueItemModel(value="blue", ratio=50),
                TraitValueItemModel(value="red", ratio=50)
            ]
        )
    ]
    
    request = GenerateImageRequestModel(
        prompt="a dragon",
        model=NFTImageModel.VELOGEN,
        height=512,
        width=512,
        traits=traits
    )
    async def generate_nft_queue(self, request_data: GenerateNFTQueueRequestModel) -> GenerateNFTQueueResponseModel
    async def generate_nft_queue_example():
        request = GenerateNFTQueueRequestModel(
            walletAddress="0x742d35Cc6635C0532925a3b8D8842A36fF20fd40",
            prompt="A mystical phoenix rising from cosmic ashes",
            model=NFTImageModel.NEBULA_FORGE_XL,  # High-quality model
            height=1024,
            width=1024,
            steps=30,
            enhance=ImageEnhanceOption.ENHANCE_1X,
            chainId=56,  # BSC Mainnet
            amount=1,
            style="cinematic"
        )
        
        response = await client.nft.generate_nft_queue(request)
        
        if response.statusCode == 201:
            print(f"NFT queued successfully!")
            print(f"Collection ID: {response.data.collectionId}")
            return response.data.collectionId
        else:
            print(f"Failed to queue: {response.message}")
            return None
    async def get_progress(self, collection_id: str) -> NFTProgressResponseModel
    async def track_progress_example(collection_id: str):
        max_attempts = 20
        attempt = 0
        
        while attempt < max_attempts:
            response = await client.nft.get_progress(collection_id)
            
            print(f"Status: {response.data.generated}")
            if response.data.progress:
                print(f"Progress: {response.data.progress}%")
            
            if response.data.generated:
                print("Generation completed!")
                if response.data.images:
                    print(f"IPFS URLs: {response.data.images}")
                return True
            
            await asyncio.sleep(15)  # Wait 15 seconds
            attempt += 1
        
        print("Timeout reached")
        return False
    async def mint_nft_metadata(self, request_data: MintNFTRequestModel) -> MintNFTResponseModel
    async def mint_metadata_example(collection_id: str):
        request = MintNFTRequestModel(
            collectionId=collection_id,
            name="Cosmic Phoenix #1",
            description="A stunning AI-generated phoenix from the ChainGPT NFT Forge.",
            symbol="CPHX",
            ids=[1]  # Single NFT
        )
        
        response = await client.nft.mint_nft_metadata(request)
        
        if response.statusCode in [200, 201]:
            print("Metadata generated successfully:")
            print(f"  ID: {response.data._id}")
            print(f"  Name: {response.data.name or 'Not provided'}")
            print(f"  Image: {response.data.image or 'Not provided'}")
            print(f"  Attributes: {response.data.attributes or 'None'}")
            print(f"  Collection ID: {response.data.collectionId or 'Not provided'}")
            print(f"  Created At: {response.data.createdAt or 'Not provided'}")
            
            # This metadata can now be used with smart contracts
            return response.data
        else:
            print(f"Failed to generate metadata: {response.message}")
            return None
    async def get_chains(self, test_net: Optional[bool] = None) -> GetChainsResponseModel
    async def get_chains_example():
        # Get mainnet chains
        mainnet_response = await client.nft.get_chains(test_net=False)
        print("Mainnet Chains:")
        for chain in mainnet_response.data.chains[:5]:
            print(f"  ID: {chain.chainId}, Name: {chain.chainName}")
        
        # Get testnet chains
        testnet_response = await client.nft.get_chains(test_net=True)
        print("\nTestnet Chains:")
        for chain in testnet_response.data.chains[:5]:
            print(f"  ID: {chain.chainId}, Name: {chain.chainName}")
        
        # Common chain IDs:
        # 1 = Ethereum Mainnet
        # 56 = BSC Mainnet
        # 137 = Polygon Mainnet
        # 97 = BSC Testnet
        # 11155111 = Ethereum Sepolia
    async def get_abi(self) -> ContractABIResponseModel
    async def get_abi_example():
        response = await client.nft.get_abi()
        
        if response.statusCode == 200:
            abi = response.data
            print(f"Contract ABI contains {len(abi)} functions/events")
            
            # Use with web3.py
            from web3 import Web3
            w3 = Web3(Web3.HTTPProvider("YOUR_RPC_URL"))
            contract = w3.eth.contract(
                address="CONTRACT_ADDRESS",
                abi=abi
            )
            
            return abi
        else:
            print(f"Failed to get ABI: {response.message}")
            return None
    class TraitModel(BaseModel):
        trait_type: str          # Name of the trait (e.g., "Background", "Color")
        value: List[TraitValueItemModel]  # Possible values with ratios
    
    class TraitValueItemModel(BaseModel):
        value: str               # Specific trait value (e.g., "night_sky")
        ratio: int              # Rarity/probability (higher = more common)
    from chaingpt.exceptions import (
        ChainGPTError,          # Base exception
        APIError,               # API-specific errors
        AuthenticationError,    # Invalid API key (401)
        ValidationError,        # Bad request (400)
        InsufficientCreditsError, # No credits (402/403)
        RateLimitError,         # Too many requests (429)
        NotFoundError,          # Endpoint not found (404)
        ServerError,            # Server errors (5xx)
        TimeoutError           # Request timeout
    )
    from chaingpt.exceptions import ChainGPTError, APIError
    
    async def safe_nft_generation():
        try:
            request = GenerateImageRequestModel(
                prompt="a dragon",
                model=NFTImageModel.VELOGEN,
                height=512,
                width=512
            )
            response = await client.nft.generate_image(request)
            return response
            
        except AuthenticationError:
            print("Invalid API key!")
        except ValidationError as e:
            print(f"Invalid request: {e.message}")
            if e.field:
                print(f"Problem with field: {e.field}")
        except InsufficientCreditsError:
            print("Not enough credits in your account")
        except RateLimitError as e:
            print(f"Rate limited. Retry after: {e.retry_after} seconds")
        except APIError as e:
            print(f"API error {e.status_code}: {e.message}")
        except ChainGPTError as e:
            print(f"General error: {e.message}")
    # Handle generation failures
    async def robust_generation(collection_id: str):
        try:
            while True:
                progress = await client.nft.get_progress(collection_id)
                
                if progress.data.generated:
                    return progress.data.images
                elif progress.statusCode >= 400:
                    raise ChainGPTError("Generation failed")
                
                await asyncio.sleep(10)
                
        except ChainGPTError as e:
            print(f"Generation error: {e}")
            return None
    import asyncio
    import os
    from chaingpt.client import ChainGPTClient
    from chaingpt.models import *
    from chaingpt.exceptions import ChainGPTError
    
    async def complete_nft_workflow():
        """Complete NFT generation workflow from prompt to metadata."""
        
        # Initialize client
        client = ChainGPTClient(api_key=os.getenv("CHAINGPT_API_KEY"))
        
        try:
            # Step 1: Enhance the prompt
            print("1. Enhancing prompt...")
            enhance_request = EnhancePromptRequestModel(
                prompt="a mystical dragon guardian"
            )
            enhanced = await client.nft.enhance_prompt(enhance_request)
            enhanced_prompt = enhanced.data.enhancedPrompt
            print(f"Enhanced: {enhanced_prompt}")
            
            # Step 2: Generate a quick preview
            print("\n2. Generating preview...")
            preview_request = GenerateImageRequestModel(
                prompt=enhanced_prompt,
                model=NFTImageModel.VELOGEN,
                height=512,
                width=512,
                enhance=ImageEnhanceOption.ORIGINAL
            )
            preview = await client.nft.generate_image(preview_request)
            
            # Save preview
            with open("preview.jpg", "wb") as f:
                f.write(bytes(preview.data.data))
            print("Preview saved as preview.jpg")
            
            # Step 3: Queue high-quality NFT generation
            print("\n3. Queueing NFT generation...")
            nft_request = GenerateNFTQueueRequestModel(
                walletAddress="0x742d35Cc6635C0532925a3b8D8842A36fF20fd40",
                prompt=enhanced_prompt,
                model=NFTImageModel.NEBULA_FORGE_XL,
                height=1024,
                width=1024,
                steps=30,
                enhance=ImageEnhanceOption.ENHANCE_1X,
                chainId=56,  # BSC Mainnet
                amount=1,
                style="fantasy-art",
                traits=[
                    TraitModel(
                        trait_type="Element",
                        value=[
                            TraitValueItemModel(value="fire", ratio=60),
                            TraitValueItemModel(value="ice", ratio=40)
                        ]
                    )
                ]
            )
            
            queue_response = await client.nft.generate_nft_queue(nft_request)
            collection_id = queue_response.data.collectionId
            print(f"Queued with ID: {collection_id}")
            
            # Step 4: Track progress
            print("\n4. Tracking progress...")
            max_attempts = 20
            for attempt in range(max_attempts):
                progress = await client.nft.get_progress(collection_id)
                print(f"Attempt {attempt + 1}: Generated: {progress.data.generated} - Progress: {progress.data.progress}%")
                
                if progress.data.generated:
                    print(f"Completed! IPFS URLs: {progress.data.images}")
                    break
                
                await asyncio.sleep(15)
            else:
                raise ChainGPTError("Generation timeout")
            
            # Step 5: Generate metadata
            print("\n5. Generating metadata...")
            metadata_request = MintNFTRequestModel(
                collectionId=collection_id,
                name="Mystical Dragon Guardian #1",
                description="An AI-generated mystical dragon guardian, protector of ancient realms.",
                symbol="MDG",
                ids=[1]
            )
            
            metadata = await client.nft.mint_nft_metadata(metadata_request)
            print("Metadata generated:")
            print(f"  ID: {metadata.data._id}")
            print(f"  Name: {metadata.data.name or 'Not provided'}")
            print(f"  Image: {metadata.data.image or 'Not provided'}")
            print(f"  Attributes: {metadata.data.attributes or 'None'}")
            
            # Step 6: Get chain info for minting
            print("\n6. Getting chain information...")
            chains = await client.nft.get_chains(test_net=False)
            bsc_mainnet = next((c for c in chains.data.chains if c.chainId == 56), None)
            if bsc_mainnet:
                print(f"Target chain: {bsc_mainnet.chainName} (ID: {bsc_mainnet.chainId})")
            
            # Step 7: Get contract ABI
            print("\n7. Getting contract ABI...")
            abi_response = await client.nft.get_abi()
            print(f"Contract ABI received (first few elements): {abi_response.data[:2]}")
            
            print("\nâś… NFT workflow completed successfully!")
            return metadata.data
            
        except ChainGPTError as e:
            print(f"❌ Error: {e}")
            return None
            
        finally:
            await client.close()
    
    # Run the complete workflow
    if __name__ == "__main__":
        result = asyncio.run(complete_nft_workflow())
    async def proper_usage():
        client = ChainGPTClient(api_key="YOUR_API_KEY")
        try:
            # Your NFT operations here
            pass
        finally:
            await client.close()
    
    # Or use async context manager if available
    async with ChainGPTClient(api_key="YOUR_API_KEY") as client:
        # Operations here
        pass
    async def robust_operation():
        try:
            # Your operation
            pass
        except AuthenticationError:
            # Handle auth issues - check API key
            pass
        except InsufficientCreditsError:
            # Handle billing issues
            pass
        except RateLimitError as e:
            # Handle rate limiting - wait and retry
            await asyncio.sleep(e.retry_after or 60)
        except ValidationError as e:
            # Handle validation errors - fix request
            print(f"Fix field: {e.field}")
    async def track_with_backoff(collection_id: str):
        wait_time = 10  # Start with 10 seconds
        max_wait = 60   # Max 60 seconds between polls
        
        while True:
            progress = await client.nft.get_progress(collection_id)
            
            if progress.data.generated:
                return progress.data.images
            
            await asyncio.sleep(wait_time)
            wait_time = min(wait_time * 1.2, max_wait)  # Exponential backoff
    # For quick previews and testing
    preview_model = NFTImageModel.VELOGEN
    
    # For final high-quality NFTs
    production_model = NFTImageModel.NEBULA_FORGE_XL
    
    # Adjust steps based on model and quality needs
    quick_steps = 10      # For previews
    quality_steps = 30    # For final NFTs
    # Good prompt structure
    prompt = "a majestic dragon, fantasy art, highly detailed, vibrant colors, mystical atmosphere"
    
    # Use enhancement for better results
    enhanced = await client.nft.enhance_prompt(
        EnhancePromptRequestModel(prompt=prompt)
    )
    final_prompt = enhanced.data.enhancedPrompt
    from pydantic import HttpUrl
    
    # Generate image based on a reference image
    request = GenerateImageRequestModel(
        prompt="a dragon in space",
        model=NFTImageModel.VELOGEN,
        height=512,
        width=512,
        image=HttpUrl("https://example.com/reference-image.jpg"),
        isCharacterPreserve=True  # Preserve character features from reference
    )
    
    response = await client.nft.generate_image(request)
    # Preserve character features
    request = GenerateImageRequestModel(
        prompt="a dragon in a cyberpunk city",
        model=NFTImageModel.NEBULA_FORGE_XL,
        height=1024,
        width=1024,
        image=HttpUrl("https://example.com/dragon-reference.jpg"),
        isCharacterPreserve=True  # Maintains dragon's appearance
    )
    traits = [
        TraitModel(
            trait_type="Background",
            value=[
                TraitValueItemModel(value="night_sky", ratio=70),
                TraitValueItemModel(value="lava_pit", ratio=30)
            ]
        ),
        TraitModel(
            trait_type="Accessory",
            value=[
                TraitValueItemModel(value="crown", ratio=20),
                TraitValueItemModel(value="sword", ratio=40),
                TraitValueItemModel(value="none", ratio=40)
            ]
        )
    ]
    chains = await client.nft.get_chains(test_net=False)
    for chain in chains.data.chains:
        print(f"Chain: {chain.chainName}")
        print(f"  ID: {chain.chainId}")
        print(f"  Network: {chain.network}")
        print(f"  Type: {chain.networkType}")
    # All responses include statusCode, message, and data
    response = await client.nft.enhance_prompt(request)
    if response.statusCode == 200:
        enhanced_prompt = response.data.enhancedPrompt
    else:
        print(f"Error: {response.message}")

    SDK Reference

    ChainGPT AI NFT Generator SDK Reference

    Introduction

    The ChainGPT AI NFT Generator SDK provides a JavaScript/TypeScript interface for generating AI-driven images and minting them as NFTs. It wraps the ChainGPT AI NFT Generator REST API, allowing developers to easily integrate image generation and NFT creation into their applications without dealing with raw HTTP requests or file handling. This reference guide covers the SDK's installation, configuration, and major functions, focusing on how to use the SDK in Node.js or web environments to create and mint AI-generated images.

    Key capabilities:

    • Generate AI art images from text prompts using ChainGPT’s proprietary models.

    • Optionally enhance (upscale) images for higher resolution outputs.

    • Create NFTs by generating an image and preparing it for minting in one flow.

    • Mint the generated image as an NFT on various blockchain networks with a single call.

    Note: This guide is for the SDK usage. If you prefer to call the REST API directly, refer to the API Reference. For a step-by-step tutorial on using the NFT Generator (with examples), see the QuickStart Guide. Ensure you have an API key from the ChainGPT platform and sufficient credits (or an appropriate subscription plan) before using the SDK (the SDK will throw an error if your API key is invalid or you run out of credits).


    Installation

    Install the SDK Package: The ChainGPT NFT Generator SDK is available as an npm package @chaingpt/nft. Add it to your project using npm or Yarn:

    This will install the SDK and its TypeScript type declarations.

    Import and initialize the SDK: The SDK exports an Nft class. Import this class and instantiate it with your API key (obtained from the ChainGPT developer dashboard):

    Only the apiKey is required to configure the SDK. The SDK uses this key to authenticate your requests to ChainGPT’s API. By default, it will use ChainGPT’s hosted endpoints—no additional setup is needed beyond providing a valid API key.

    Note: Keep your API key secure (do not hard-code it in client-side code or expose it publicly). Also ensure you have sufficient API credits or an active plan to perform NFT generations. If your key is invalid or you exceed your quota, the SDK will throw an Errors.NftError (see Error Handling below).


    SDK Usage

    Below are the primary methods provided by the Nft SDK instance. Each method is documented with its purpose, expected parameters, return values, and example usage.

    generateImage(options)

    Description: Generates an image from a text prompt using one of ChainGPT’s AI models, returning the image data. This function does not mint an NFT; it only performs image generation. Use generateImage when you want to create an image (for example, to let a user preview it) without immediately putting it on-chain. To generate an image and directly prepare it for minting, use generateNft() instead.

    Parameters: (passed as properties of the options object)

    • prompt (string, required): The text prompt describing the desired image. This can be any creative description of the image you want (e.g. "A futuristic city skyline at sunset, neon pink and orange hues").

    • model (string, required): The identifier of the AI model to use for generation. Supported models include velogen, nebula_forge_xl, VisionaryForge. Each model has a different style or aesthetic (e.g. photorealistic, anime, 3D render, etc.). ChainGPT’s proprietary models are

    Note on image size: Supported width × height combinations (aspect ratios) depend on the model (and whether enhancement is used). For example, Velogen supports base resolutions like 512×512 (square), 768×512 (landscape), 512×768 (portrait). With 2× enhancement, it can produce up to ~1920×1920 (square) and corresponding larger rectangles. Nebula Forge XL and VisionaryForge have their own supported dimensions (see Supported Models & Settings below for detailed resolution options). If you request a size that the model doesn’t support, the API may return an error or adjust to the nearest valid size. If height/width are not specified, the SDK will default to the model’s base default (usually a square format such as 512×512 or 1024×1024 depending on the model).

    Returns: A Promise that resolves to an object containing the generated image data. On success, you can expect the image bytes (binary data) to be available (typically under a field like data or similar). The image is in JPEG format by default. You can take the returned binary data and save it to a file, send it to a client, or further process it as needed.

    Example – Generate an image and save to a file (with explanations):

    Example –Generate an image to image using Velogen

    In this example, we used the velogen model to generate a 1024Ă—1024 image from the given prompt, with a single upscaling enhancement. The resulting image bytes are written to generated-image.jpg. After running this code, that file will contain the AI-generated artwork. You can adjust the prompt, model, and other parameters as needed

    Example – Character Reference NFT Image Generation

    Note: If isCharacterPreserve is set to true, you must also provide a valid image URL. It will charge an extra 5 credits.

    Multiple NFT Images Generation

    This SDK accepts multiple prompts, generates multiple images, and saves them to a folder according to the specified parameters

    Synchronous NFT Generation

    generateNft(options)

    Description: Generates an image and prepares NFT metadata from a text prompt, intended for minting. This call handles the AI image creation similarly to generateImage(), but also registers the result for minting (on ChainGPT’s backend) and returns metadata needed to proceed with minting. Typically, after generateNft completes, you would call mintNft() to actually mint the NFT on-chain. This method is synchronous in the sense that it waits for the image generation to finish before returning, so it can take some time (usually 30–60 seconds for the image to be generated). Under the hood, this corresponds to an API call that generates the image and prepares the NFT in one step.

    Parameters: (passed in an options object; includes all generateImage parameters plus NFT-specific fields)

    • All image generation parameters from generateImage(): You can include prompt, model, enhance, steps, width, height with the same meanings as described above. These control the image generation part of this call.

    • walletAddress

    (There are no parameters for NFT name/description in this step – those are provided later to the mintNft() call.)

    Returns: A Promise that resolves to an object containing the generated NFT data. On success, the result will include:

    • The image data (similar to what generateImage returns, i.e. the binary image bytes).

    • A collectionId (string or UUID) that uniquely identifies this generation job and the associated metadata on ChainGPT’s backend.

    The collectionId is important: it references the saved AI-generated image and metadata. You will use it to either check the generation status (if queued) or to mint the NFT. In the case of generateNft() (synchronous), the promise only resolves after the image is fully generated, so at that point the image is ready and collectionId can be used directly for minting.

    Note: After generateNft() completes, the NFT is not yet on the blockchain. It’s essentially a prepared record (image + metadata) awaiting the minting step. You must call mintNft() with the returned collectionId to actually mint the NFT on-chain. This two-step process (generate then mint) allows you to, for example, confirm with a user or display the image before incurring blockchain costs.

    Example – Generate an NFT then mint it (with explanations):

    In this example, we first call generateNft() with a prompt and parameters including the wallet address and chain ID where we want to mint. When this completes, we get a collectionId (printed to console) which references the generated image and metadata. We then call mintNft() with that collectionId and provide an NFT name, description, and symbol. The SDK then handles the blockchain transaction to mint the NFT to the specified address on BSC Testnet (chainId 97). The mintResult would contain information about the minting operation (such as a transaction hash or token ID, depending on the implementation).

    Example – Production usage (generate then mint, minimal code):

    The above snippet omits comments for brevity. It generates an NFT on BSC (chain 56) for the given wallet address, then immediately mints it with a name, description, and symbol. In a real application, you should include error handling around these calls (e.g., try/catch) and perhaps update your UI to inform the user of progress between generation and minting.

    generateNftWithQueue(options) – Asynchronous/Queued Generation

    Description: Initiates an NFT generation task asynchronously, without waiting for the image to be fully generated. This function returns quickly with a collectionId that represents the queued generation job on ChainGPT’s servers. The actual image creation then happens in the background. You can use the returned collectionId to poll the job’s status via getNftProgress() and later call mintNft() to mint the NFT once the image is ready. This queued approach is useful for handling multiple generations in parallel or offloading longer generation times without blocking your application flow.

    Parameters: Same as generateNft(options) above. You must provide all required fields (prompt, model, walletAddress, chainId) and any optional generation settings (enhance, steps, height, width) as needed.

    Returns: A Promise that resolves to an object containing at least a collectionId for the queued generation request. The image data will not be available immediately in the response, since generation is still in progress. The collectionId is the key identifier you'll use to check progress and eventually mint the NFT. Essentially, if this call succeeds, it means the generation job was accepted and is now processing on the server.

    Example – Queue an NFT generation and check progress (with explanations):

    In this example, we queue an NFT generation using generateNftWithQueue(). The call returns immediately with a collectionId (stored in jobId). We then enter a loop to poll the job’s status using getNftProgress(), every 5 seconds, logging the progress percentage. Once the status becomes "completed" (which implies 100% progress), we proceed to call mintNft() with the same collectionId to mint the NFT on-chain. In a real application, you might use a longer delay between polls or integrate a webhook/callback if available, rather than busy polling. You can also queue multiple jobs in parallel and poll each one, which makes this approach suitable for generating large collections of NFTs asynchronously.

    Example – Production usage (queue generation, minimal):

    Here we simply queue the generation and log the job ID. The subsequent steps (polling progress and minting) would be similar to the detailed example above. This pattern allows your code to continue doing other work or handling other requests while images are being generated in the background.

    getNftProgress(options)

    Description: Checks the status of an NFT generation job that was started with generateNftWithQueue() (or even a generateNft() call if you want to poll its progress, though generateNft() usually waits internally). It returns information about the generation progress, such as a percentage complete or a status indicator.

    Parameters:

    • collectionId (string, required): The unique identifier of the NFT generation job to query. This is the collectionId returned by generateNft or generateNftWithQueue. Without a valid collectionId, the API cannot identify which job’s status to retrieve.

    Returns: A Promise that resolves to an object containing progress information for the specified job. The exact structure of the data may include fields like progress (number) and status (string). For example, a successful response might be { progress: 100, status: "completed", ... } when the generation is finished. Before completion, you might see a lower progress value (e.g. 0 to 99) and a status like "processing" or "queued". If an invalid collectionId is provided, the SDK will throw an error or you might get a response indicating the job wasn’t found.

    Typically, you will call this method repeatedly (polling) until the status is "completed" or progress reaches 100, then proceed to mint the NFT. The frequency of polling can be adjusted based on how long generations typically take (e.g., polling every few seconds).

    Example – Basic usage:

    Example – Production snippet (single progress check):

    In practice, you would integrate this into a loop or schedule as shown in the queued generation example. Use getNftProgress() to inform users about the generation status (e.g., a loading bar) or to trigger the next step of your workflow when the image is ready.

    mintNft(options)

    Description: Mints an NFT on the specified blockchain, using a previously generated image/metadata. This is the final step in the NFT creation process, taking the output of generateNft (identified by a collectionId) and writing the NFT to the blockchain. The method also lets you set the NFT’s name, description, and symbol (metadata) if they weren't already set. Under the hood, this will interact with ChainGPT’s NFT minting smart contract to either create a new NFT in an existing collection or deploy a new collection, then mint the token to the provided wallet address.

    Parameters:

    • collectionId (string, required): The ID of the generated NFT content to mint. This is obtained from a prior generateNft or generateNftWithQueue call. It tells the system which image/metadata to use for minting.

    • name (string, required): The name for the NFT. This could be the title of the artwork or any descriptive name. This will appear as the token’s name in metadata.

    Returns: A Promise that resolves to an object containing the result of the mint operation. On success, this will typically include details such as:

    • Confirmation that the NFT was minted (e.g., a success status or the minted token’s ID/URL).

    • Transaction details, like a transaction hash, if the mint involved an on-chain transaction.

    • Possibly the address of the new NFT collection contract (if one was deployed) or confirmation of the collection used.

    The exact fields returned may vary, but the key outcome is that the image identified by collectionId is now minted as an NFT owned by walletAddress (which was provided during generation). The promise will only resolve once the minting is complete (which may involve waiting for a blockchain transaction).

    After calling mintNft(), the NFT is live on the blockchain. You can then fetch it from the blockchain or via ChainGPT’s APIs, and it will have the metadata (name, description, etc.) that you provided.

    Example – Mint an NFT directly (assuming image is already generated):

    In this example, we directly call mintNft() using a known collectionId (from a prior generation step) and provide the desired metadata. If the operation succeeds, the console will log a success message. In a real scenario, you’d want to wrap this in a try/catch to handle errors (like network issues or insufficient permissions) and perhaps confirm the transaction result.

    Example – Production snippet:

    Typically, you will call mintNft() once per generated image to put it on-chain. Remember to catch errors from this call as it involves external blockchain interaction (see Error Handling below). For instance, if the user’s wallet is invalid or if there are network fees required that the system cannot cover, you would get an error.

    Enhance Your Prompt

    Update your prompt by setting the enhancement level to receive a response tailored to the enhanced prompt.


    Generate Random Prompt (Surprise Me)

    Run this snippet of code to receive a surprise prompt for generating an NFT.

    Get Collections with Filters

    This example demonstrates how to use the @chaingpt/nft SDK to retrieve NFT collections associated with a specific wallet address.

    Parameters

    Parameter
    Type
    Required
    Description

    Toggle NFT Visibility

    toggle the visibility status (e.g., from public to private or vice versa) of an NFT collection using the @chaingpt/nft SDK.

    Supported Models & Settings

    (This section provides reference details on the supported AI models, image enhancements, and output formats available in the ChainGPT NFT Generator SDK.)

    • Supported AI Models: You can choose from several AI models via the model parameter in generateImage/generateNft:

      • velogen – ChainGPT’s VeloGen model, suitable for realistic or general-purpose image generation.


    Error Handling

    The ChainGPT NFT SDK provides a structured error handling mechanism to help you catch and manage errors from any SDK call (image generation, minting, etc.).

    When something goes wrong (such as a network issue, an invalid API request, or an error returned from the ChainGPT API), the SDK will throw an error of type Errors.NftError. This is a custom error class provided by the SDK. It includes a message describing the error, and it may include additional information such as an HTTP status code or an error payload from the API.

    How to handle errors: Ensure you wrap your SDK calls in a try...catch block in your async function. In the catch, you can check if the caught error is an instance of Errors.NftError to distinguish it from other types of exceptions.

    Example – Error handling pattern:

    In the above snippet, if nft.generateNft() fails (for example, due to an invalid API key, a 400 Bad Request from the API, or a network timeout), the catch block will execute. The error’s message (error.message) usually provides a human-readable description of what went wrong (e.g. "Unauthorized" for invalid API key, or a specific validation message). By checking instanceof Errors.NftError, we ensure we’re handling errors thrown by the ChainGPT SDK. Any other error would fall to the else block (which could be a coding mistake or something unrelated).

    Common error scenarios to handle:

    • Authentication failures: If your API key is missing, incorrect, or expired, the SDK will throw an NftError (often indicating a 401 or 403 HTTP error under the hood). You should catch this and prompt for a correct key or notify about invalid credentials.

    • Invalid parameters: If you pass values that the API cannot process (e.g., an unsupported image resolution, or missing a required field like walletAddress), the API will respond with a 400 error and the SDK will throw an NftError with details. Check the message to adjust your request.

    By consistently catching Errors.NftError, you can gracefully handle all these cases. The SDK abstracts away the need to manually parse HTTP responses; any non-2xx HTTP response or other failure will result in a thrown NftError that you can catch in one place. This makes it easier to implement robust error-handling logic (such as retries, user notifications, or logging) around SDK calls.


    Additional Resources

    • ChainGPT Developer Dashboard: To obtain your API key or manage your subscription/credits, visit the ChainGPT Developer Dashboard on the ChainGPT website. This is where you can monitor your usage and top up credits if needed.

    • Pricing & Credits: For details on how the credit system works and the cost of generating images or NFTs, refer to the Pricing & Membership Plans page on the ChainGPT documentation site. (Pricing is subject to change and depends on the model and enhancements used, so it’s maintained separately from this SDK reference.)

    • NPM Package Documentation: You can find the SDK’s package page on , which may include additional usage examples and the latest version information.

    This SDK reference is meant to be a comprehensive guide for developers. For any further help, check out the QuickStart guide for step-by-step examples or contact the ChainGPT support team. Happy building with the ChainGPT AI NFT Generator SDK!

    API Reference

    ChainGPT AI NFT Generator API Reference

    Introduction

    This reference describes the RESTful API endpoints for the ChainGPT AI NFT Generator. It covers endpoints for generating AI-based images and NFTs, along with supporting endpoints for prompt enhancement, chain information, and contract ABI. Each endpoint is documented with its method, path, required headers, parameters, and example requests/responses. Use this guide to integrate AI image generation and NFT minting into your applications.

    Check generation progress for queued jobs and retrieve supported blockchain info.

  • Enhance text prompts for better image generation results.

  • velogen
    ,
    nebula_forge_xl
    , and
    VisionaryForge
    .
  • image (string(Url), optional): The image URL to use as the base or reference (can be left out if you want pure text-to-image).

  • enhance (string, optional): Image enhancement/upscaling level. Use "1x" for single enhancement, "2x" for double enhancement, or omit / use an empty string for no enhancement. Enhancement will upscale the image (improving resolution/quality) and is only supported by certain models (currently velogen, nebula_forge_xl, VisionaryForge). If an unsupported model is used with this parameter, the enhancement request is ignored.

  • steps (number, optional): The number of diffusion or refinement steps to use for image generation. More steps can produce more detailed or refined images at the cost of longer generation time. Each model has its own supported range (e.g. velogen supports 1–4 steps, default is 2; nebula_forge_xl & VisionaryForge supports up to 50, default is 25). If not provided, the model’s default number of steps is used.

  • width (number, optional): The width of the generated image in pixels.

  • height (number, optional): The height of the generated image in pixels.

  • style (string, optional): If you include a style, the image will be generated according to the specified style. Available styles are listed below. (Listed Styles)

  • isCharacterPreserve (bool, optional): Tells the generator to preserve the main character’s identity and features from the reference image (image URL) while still applying the prompt.

  • traits (Array , optional): Traits are an optional array of objects. If provided, images will be generated based on the specified trait ratios. For example, if the array includes two traits—Background with values Heaven (ratio: 20) and Hell (ratio: 60)—and you request 5 images, approximately 1 will use Heaven and 3 will use Hell background.You can adjust traits and ratios to guide image generation accordingly.

  • (string,
    required
    ): The public wallet address that will eventually own the NFT. This is the address to which the NFT will be minted (transferred) when you call
    mintNft()
    . Make sure this is a valid address on the blockchain network you intend to use.
  • chainId (number, required): The blockchain network ID where the NFT will be minted. ChainGPT’s NFT generator supports many networks (Ethereum, BNB Chain, Polygon, Arbitrum, Avalanche, Tron, and more). For example: use 1 for Ethereum Mainnet, 56 for BNB Smart Chain (BSC) Mainnet, 137 for Polygon, etc. You can retrieve the full list of supported networks and their IDs at runtime with the getChains() method. Ensure the chainId you provide corresponds to the network of the provided wallet address.

  • style (string, optional): If you include a style, the image will be generated according to the specified style. Available styles are listed below. (Listed Styles)

  • traits (Array , optional): Traits are an optional array of objects. If provided, images will be generated based on the specified trait ratios. For example, if the array includes two traits—Background with values Heaven (ratio: 20) and Hell (ratio: 60)—and you request 5 images, approximately 1 will use Heaven and 3 will use Hell background.You can adjust traits and ratios to guide image generation accordingly.

  • description (string, optional): A text description for the NFT. This is stored in the token’s metadata, providing details or context for the artwork. (If not provided, it might be left blank or a default in the metadata.)
  • symbol (string, optional): The symbol (short identifier) for the NFT collection. If this minting operation creates a new NFT collection (smart contract), this symbol will be used for that collection (similar to a ticker or shorthand for the collection). If the NFT is being minted into an existing collection, this parameter might be ignored. For one-off mints or testing, you can use any short string (e.g. "AI" or "ART").

  • isMinted

    boolean

    ❌

    Filter by minted status

    name

    string

    ❌

    Filter by collection name

    symbol

    string

    ❌

    Filter by token symbol

    page

    number

    ❌

    Pagination: page number

    limit

    number

    ❌

    Pagination: number of items per page

    nebula_forge_xl – ChainGPT’s high-resolution model, useful for detailed and high-quality imagery.
  • VisionaryForge – ChainGPT’s creative model for artistic or concept art styles.

  • Dale3 – An integration of OpenAI’s DALL·E 3 model (optional). This model can be used for varied art styles and compositions, though it may not support all the advanced settings (enhancements, etc.) that the ChainGPT proprietary models do.

  • Each model has different strengths and styles. We recommend experimenting with the proprietary models (velogen, nebula_forge_xl, VisionaryForge) to see which best suits your use case.

  • Image Formats: Generated images are returned in a binary form (typically a buffer containing JPEG data). By default, the images generated via the API/SDK are in JPEG format (as seen by the .jpg extension in examples). The SDK itself does not expose a parameter to select the image format (e.g., PNG vs JPEG); it will always return the image data as provided by the API (JPEG). If you require a different format, you can convert the image bytes to another format using an image processing library after you receive the data.

  • Enhancement (Upscaling) Options: The enhance parameter allows you to request higher-resolution outputs:

    • "1x" – Single enhancement (image is upscaled once, roughly doubling the resolution).

    • "2x" – Double enhancement (upscaled twice, resulting in an even larger image).

    Only certain models support enhancement/upscaling (currently velogen, nebula_forge_xl, and VisionaryForge). Using "1x" or "2x" with those models will produce larger, more detailed images (as shown in their supported resolutions below). If you attempt to enhance on a model that doesn’t support it (such as Dale3), the request will simply generate at the model’s default resolution without upscale. Keep in mind that enhanced images consume more processing and may count as additional credit usage.

  • Resolution & Aspect Ratios: Each model supports specific image resolutions, especially when using enhancement:

    • Velogen: Base output resolutions include 512Ă—512 (square), 768Ă—512 (landscape), 512Ă—768 (portrait). With 2Ă— enhancement, approximate maximum resolutions are 1920Ă—1920 (square), 1920Ă—1280 (landscape), 1280Ă—1920 (portrait).

    • Nebula Forge XL: Base outputs are 1024Ă—1024, 1024Ă—768, 768Ă—1024. With upscaling (enhancement), it can go up to ~1536Ă—1536 (square), 1536Ă—1024 (landscape), 1024Ă—1536 (portrait).

    • VisionaryForge: Base outputs are 1024Ă—1024, 1024Ă—768, 768Ă—1024 (similar to Nebula’s base). With upscaling, up to around 1536Ă—1536, 1536Ă—1024, 1024Ă—1536.

    • Dale3: (1024x1024, upscaling or enhancement isn't available).

    When specifying the width and height in your requests, it’s best to stick to one of the supported aspect ratio combinations for the chosen model (as listed above) to get optimal results. If you choose a non-standard size, the API might adjust the output size or return an error. For simplicity, using a square resolution (512×512 for smaller images, or 1024×1024 for larger images) is a safe choice across models.

  • Default Values: If you omit certain optional parameters in the generation calls:

    • enhance – Defaults to no enhancement (no upscaling) if not provided.

    • steps – Defaults to the model’s built-in default (for example, 2 steps for VeloGen, 25 for Nebula Forge XL) if not specified.

    • height/width – Typically default to the model’s default resolution (often the base square, e.g., 512Ă—512 for some models or 1024Ă—1024 for others). It’s recommended to explicitly set these for clarity.

  • Generation failures: In rare cases, the AI might fail to generate an image or the job might encounter an internal error. This could result in an error or a job status that indicates failure. Handle this by catching the error or checking for a failure status in getNftProgress().
  • Network issues: If the SDK cannot reach the ChainGPT API (due to network outage or timeout), it will throw an NftError indicating a network error. You might implement retries or inform the user to check their connection.

  • REST API Reference: If you need to use the NFT generator via HTTP calls or want to know the underlying endpoints, consult the AI NFT Generator API Reference in the ChainGPT docs.

  • Support & Community: If you encounter issues or have questions, you can reach out through ChainGPT’s official support channels. Visit the ChainGPT website ChainGPT.org for links to community forums, Discord, or contact information. The development team and community are available to help with integration questions or troubleshooting.

  • walletAddress

    string

    âś…

    The wallet address to fetch collections for

    isPublic

    boolean

    ❌

    Filter only public collections

    isDraft

    boolean

    ❌

    npmjs.com

    Filter by draft status

    npm install --save @chaingpt/nft
    # or
    yarn add @chaingpt/nft
    // Import the Nft class from the SDK
    const { Nft } = require('@chaingpt/nft');  // CommonJS
    // import { Nft } from '@chaingpt/nft';    // ES Module / TypeScript
    
    // Initialize the SDK with your API key
    const nft = new Nft({
      apiKey: 'YOUR_API_KEY_HERE'  // ChainGPT API Key for authentication
      // ... you can include other config options if supported
    });
    const fs = require('fs');
    
    async function main() {
      const generatedImage = await nft.generateImage({
        prompt: 'cars racing to the finish', // Prompt to be used to generate the NFT art
        model: 'velogen', // Model to be used to generate the NFT art
        enhance: 'original', // enhance imgae once or twice
        steps: 2, // steps parameter passed while image generation
        height: 512, //height of the resulting image
        width: 512, // width of the resulting image
        style: 'cinematic', //sample value for style
        traits: [
          {
            trait_type: 'Background',
            value: [
              { value: 'Heaven', ratio: 20 },
              { value: 'Hell', ratio: 60 },
              { value: 'garden', ratio: 20 },
            ],
          },
          {
            trait_type: 'contrast',
            value: [
              { value: 'dark', ratio: 20 },
              { value: 'light', ratio: 80 },
            ],
          },
        ],
      });
    
      // Save the buffer directly to a file
      fs.writeFileSync('generated-image.jpg', Buffer.from(generatedImage.data.data));
    }
    
    main()
    const fs = require('fs');
    
    async function main() {
      const generatedImage = await nft.generateImage({
        prompt: "medieval fantasy knight, wearing armor", // Prompt to be used to generate the NFT art
        image: "https://chaingpt.s3.dualstack.us-east-2.amazonaws.com/sdk/cgpt-bot.jpg",
        model: 'velogen', // Model to be used to generate the NFT art
        enhance: 'original', // enhance imgae once or twice
        steps: 3,
        height: 1024, //height of the resulting image
        width: 1024, // width of the resulting image
    
      });
    
      // Save the buffer directly to a file
      fs.writeFileSync('generated-image.jpg', Buffer.from(generatedImage.data.data));
    }
    
    main();
    const fs = require('fs');
    
    async function main() {
      const generatedImage = await nftInstance.generateImage({
        prompt: "musician playing guitar under stage lights", // Prompt to be used to generate the NFT art
        image: "https://chaingpt.s3.dualstack.us-east-2.amazonaws.com/sdk/cgpt-bot.jpg",
        model: 'velogen', // Allowed models velogen, VisionaryForge, nebula_forge_xl
        enhance: 'original', // enhance image once pass '1x' or twice pass '2x'
        steps: 3,
        height: 1024, //height of the resulting image
        width: 1024, // width of the resulting image
        isCharacterPreserve: true // to preserve the character
    
      });
    
      // Save the buffer directly to a file
      fs.writeFileSync('generated-image.jpg', Buffer.from(generatedImage.data.data));
    }
    
    main();
    const { Nft } = require('@chaingpt/nft');
    const fs = require('fs');
    
    const nftInstance = new Nft({
      apiKey: 'Your ChainGPT API Key',
    });
    
    async function main() {
        const generatedImages = await nftInstance.generateMultipleImages({
          prompt: [
            'cars racing to the finish', 
            'bot running in the jungle'
          ],
          model: 'velogen',
          enhance: '1x',
          steps: 2,
          height: 512,
          width: 512,
          style: 'cinematic',
          image: "https://chaingpt.s3.dualstack.us-east-2.amazonaws.com/sdk/cgpt-bot.jpg",
          isCharacterPreserve: true
        });
        // Save each buffer directly to a file
        generatedImages.forEach((buffer, index) => {
            const filename = `generated-image-${index + 1}.jpg`;        
            fs.writeFileSync(filename, buffer);
            console.log(`Saved image ${index + 1} to: ${filename}`);
        });
    }
    
    main();
    
    // 1. Generate the NFT image and metadata (synchronously)
    const genResult = await nft.generateNft({
      prompt: "A cute cartoon cat astronaut, sticker illustration",
      model: "VisionaryForge",
      enhance: "",             // no enhancement (empty string or omit for none)
      height: 1024, width: 1024,
      walletAddress: "0xABC123...DEF",  // the recipient wallet address for the NFT
      chainId: 97,                      // target chain ID (97 = BSC Testnet in this example)
      amount:1,                 //The number of images generated for the collection.
       style: 'cinematic',       //Style of image
      traits: [
          {
            trait_type: 'Background',
            value: [
              { value: 'Heaven', ratio: 20 },
              { value: 'Hell', ratio: 60 },
              { value: 'garden', ratio: 20 },
            ],
          },
          {
            trait_type: 'contrast',
            value: [
              { value: 'dark', ratio: 20 },
              { value: 'light', ratio: 80 },
            ],
          },
        ],
    });
    console.log("Generation completed. Collection ID:", genResult.data.collectionId);
    
    // 2. Mint the generated NFT on-chain using the returned collectionId
    const mintResult = await nft.mintNft({
      collectionId: genResult.data.collectionId,  // use the collectionId obtained from generateNft
      name: "Space Cat Sticker",                  // human-readable name for the NFT
      description: "An AI-generated cat astronaut sticker, created via ChainGPT",  // description metadata
      symbol: "CAT",                               // symbol for the NFT collection (if a new collection is created)
      ids: [1,....,n]
    });
    console.log("NFT minted! Transaction/result:", mintResult);
    // Generate NFT (blocking until ready) and then mint it on BSC Mainnet
    const { data: nftData } = await nft.generateNft({ 
      prompt: "Epic dragon portrait in medieval style", 
      model: "velogen",
      walletAddress: "0x...YOUR_WALLET_ADDRESS", 
      chainId: 56,  // BNB Chain Mainnet
      height: 512,
      width: 512,
      amount:1
    });
    await nft.mintNft({
      collectionId: nftData.collectionId,
      name: "Epic Dragon", 
      description: "AI-generated medieval dragon art", 
      symbol: "DRGN"
    });
    // 1. Start the NFT generation job (async queue)
    const queueResult = await nft.generateNftWithQueue({
      prompt: "Abstract colorful swirl painting, high resolution",
      model: "nebula_forge_xl",
      walletAddress: "0xDEF456...789",
      height: 512,  
      width: 512,
      amount: 1,
      chainId: 1   // Ethereum Mainnet
    });
    const jobId = queueResult.data.collectionId;
    console.log("Generation queued. Collection ID:", jobId);
    
    // 2. Periodically check the generation progress
    let progressInfo;
    do {
      progressInfo = await nft.getNftProgress({ collectionId: jobId });
      const percent = progressInfo.data.progress;   // e.g., progress percentage
      console.log(`Generation progress: ${percent}%`);
      await new Promise(res => setTimeout(res, 5000));  // wait 5 seconds before checking again
    } while (progressInfo.data.status !== "completed");
    // Loop until the status indicates completion (status might go from "processing" to "completed")
    
    console.log("Generation complete! Now minting the NFT...");
    // 3. Mint the NFT now that the image generation is done
    await nft.mintNft({
      collectionId: jobId,
      name: "Color Swirl Art",
      description: "AI-generated abstract painting",
      symbol: "ART"
    });
    console.log("NFT minted on chain.");
    // Queue NFT generation (non-blocking call)
    const { data: queued } = await nft.generateNftWithQueue({ 
      prompt: "Portrait of an AI robot", 
      model: "velogen", 
      walletAddress: "0x...ADDR", 
      height: 512,
      width: 512,
      amount: 1,
      chainId: 137  // Polygon Mainnet
    });
    console.log("Queued job ID:", queued.collectionId);
    // (Later, use getNftProgress() and mintNft() as shown above once the job is done)
    const progressRes = await nft.getNftProgress({ collectionId: jobId });
    if (progressRes.data.progress === 100) {
      console.log("Job completed!");
    }
    // Check the current progress of a generation job
    const status = await nft.getNftProgress({ collectionId: "YOUR_COLLECTION_ID" });
    console.log("Current progress:", status.data.progress, "%");
    await nft.mintNft({
      collectionId: "abcd1234-ef56-...-xyz",  // collection ID from a previous generateNft call
      name: "My AI Artwork",
      description: "This NFT image was generated by AI via ChainGPT",
      symbol: "AINFT",
      ids: [1,....,n]
    });
    console.log("Mint successful!");
    // Finalize NFT minting (production use)
    const result = await nft.mintNft({ collectionId, name: "Artwork #1", symbol: "ART" });
    // (Add error handling as needed)
    const { Nft } = require('@chaingpt/nft');
    const nftInstance = new Nft({ apiKey: 'Your ChainGPT API Key' });
    
    async function main() {
      const enhancedPrompt = await nftInstance.enhancePrompt({
        prompt: 'lion in jungle',
      });
      console.log(enhancedPrompt);
    }
    main();
    const { Nft } = require('@chaingpt/nft');
    const nftInstance = new Nft({ apiKey: 'Your ChainGPT API Key' });
    
    async function main() {
      const randomPrompt = await nftInstance.surpriseMe();
      console.log(randomPrompt);
    }
    main();
    const { Nft } = require('@chaingpt/nft');
    const nftInstance = new Nft({ apiKey: 'Your ChainGPT API Key' });
    
    async function main() {
      const collections = await nftInstance.getCollections({
        walletAddress: '<wallet address>', 
        isPublic: true,
         isDraft: false, 
         isMinted: false, 
         name: "<name>", 
         symbol: "<symbol>", 
        page: 1,
        limit: 10,
      });
      console.log(collections);
    }
    main();
    const { Nft } = require('@chaingpt/nft');
    const nftInstance = new Nft({ apiKey: 'Your ChainGPT API Key' });
    
    async function main() {
      const response = await nftInstance.toggleNftVisibility({
        collectionId: '<collection id>',
      });
      console.log(response);
    }
    main();
    import { Errors } from '@chaingpt/nft';
    
    try {
      const response = await nft.generateNft({ /* ...parameters... */ });
      // Use the response normally if successful
    } catch (error) {
      if (error instanceof Errors.NftError) {
        console.error("ChainGPT SDK error:", error.message);
        // You could also inspect error.response or error.code if needed
      } else {
        // Some other unexpected error (programming error, etc.)
        console.error("Unexpected error:", error);
      }
    }

    Authentication & API Basics

    • Base URL: All endpoints are relative to the base URL https://api.chaingpt.org.

    • API Key (Authentication): Every request must include your API key in the Authorization header as a Bearer token. For example:

      You can obtain an API key from the ChainGPT web app’s API dashboard (after acquiring credits). Ensure the API key has sufficient credits in your account (see Pricing & Credits). Requests without a valid key will be rejected with 401 Unauthorized.

    • Content Type: Use Content-Type: application/json for request bodies, and expect JSON responses. Image data is returned encoded in JSON (e.g. as an array of bytes or base64 string).

    • Models: The AI NFT Generator supports multiple image models. When generating images, you must specify one of the supported models: "velogen", "nebula_forge_xl", "VisionaryForge", or "Dale3" (which uses OpenAI’s DALL·E 3). Each model has specific constraints on image resolution and steps (see Supported Models & Parameters). Choose the model appropriate for your needs (e.g. VeloGen for quick small images, NebulaForge XL or VisionaryForge for high quality larger images, or DALL·E 3 for its unique generative capabilities).


    Text-to-Image Generation (Synchronous)

    Use this endpoint to generate an image from a text prompt and get the result immediately. The API will return the image data (as a binary buffer or encoded string) in the response synchronously. This is ideal for quick image generation (e.g. previews or single images) when you don't need NFT minting.

    POST /nft/generate-image

    Description: Generates an image based on the given prompt and model. The image bytes are returned directly in the response (no need to poll for results). For supported models, resolutions, and steps, see the Supported Models & Parameters section.

    Headers:

    • Authorization: Bearer YOUR_API_KEY (required)

    • Content-Type: application/json (required)

    Request Body Parameters:

    Parameter

    Type

    Description

    prompt

    string (required)

    The text prompt describing the image to generate.

    model

    string (required)

    Identifier of the model to use (e.g. "velogen", "nebula_forge_xl", "VisionaryForge", or "Dale3" for DALL·E 3).

    steps

    integer (optional)

    Number of refinement passes for image generation. Higher values can yield more detailed images at the cost of longer generation time. Each model supports a range: for example, velogen supports 1–4 steps (default ~2), while NebulaForge XL and VisionaryForge support up to 50 (default ~25). If not provided, a model-specific default is used.

    height

    integer (required)

    Output image height in pixels. Must be within the model’s supported base resolution range (see Supported Models & Parameters). Common values are 512 or 768 for base generation, or larger if using enhancement.

    Sample Request:

    Sample Response:

    The response’s data field contains the raw image bytes. For example, the above byte array begins with 255, 216, 237, ..., which corresponds to the JPEG file header. To use the image, you can write these bytes to a file or decode them in your application. For instance, in Node.js you could do:

    This will save the returned image buffer to an output.jpg file. (If the API returns image data as a base64-encoded string instead, you would decode it accordingly.)

    Multiple NFT Images Generation

    This API allows you to generate multiple images based on specified prompts and parameters.


    Text-to-NFT Generation (Asynchronous)

    Use these endpoints to generate an image intended for NFT minting. The generation is handled asynchronously: first you queue a generation job, then poll for its progress, and finally retrieve the NFT metadata for minting. This flow is suited for higher resolution images or cases where you plan to mint the result as an NFT on a blockchain.

    POST /nft/generate-nft-queue

    Description: Initiates an NFT image generation job with the specified parameters, associating it with a blockchain and wallet for eventual minting. Unlike the immediate image endpoint, this returns quickly with a job identifier (collectionId) while the image is generated in the background. You should subsequently use the progress endpoint to check when the image is ready. This queued approach is recommended for longer-running jobs or when an on-chain mint will follow.

    Headers:

    • Authorization: Bearer YOUR_API_KEY (required)

    • Content-Type: application/json (required)

    Request Body Parameters:

    Parameter

    Type

    Description

    walletAddress

    string (required)

    The blockchain wallet address that will own the minted NFT. This should be a valid address on the target chain (e.g. the user’s wallet).

    prompt

    string (required)

    The text prompt for image generation (same usage as in the direct image endpoint).

    model

    string (required)

    The model to use (e.g. "velogen", "nebula_forge_xl", "VisionaryForge", "Dale3"). Supports the same options and constraints as the direct image generation endpoint.

    steps

    integer (optional)

    Number of generation steps (refinement passes). Defaults to the model’s optimal value if not provided. You may use higher values (up to the model’s max, e.g. 50 for NebulaForge XL/VisionaryForge) to improve quality.

    Sample Request:

    Sample Response (Queued):

    On success, the API returns a unique collectionId for the requested generation, along with an initial status (typically "queued" or "processing"). No image data is returned at this stage. You must use the collectionId with the Progress endpoint (described next) to poll for completion and retrieve the image or metadata once the generation is finished.

    Note: Use the NFT queue endpoint (with walletAddress and chainId) if you plan to mint the result as an NFT on-chain. If you only need an image and do not intend to mint it, use the direct POST /nft/generate-image endpoint instead. The underlying image generation is similar, but the queued flow enables tracking progress and later minting.

    Track Generation Progress - GET /progress/{collectionId}

    Description: Checks the status and progress of a queued NFT generation job identified by its collectionId. Use this endpoint to poll for completion when you have initiated a job via generate-nft-queue. It returns whether the job is still processing or completed (and may include the result when done).

    Path Parameter:h

    • {collectionId} (string, required) – The ID of the NFT generation job, as returned by the generate-nft-queue call.

    Headers:

    • Authorization: Bearer YOUR_API_KEY (required)

    • (No request body, this is a GET request.)

    Sample Request:

    Sample Response (In Progress):

    In the above example, the generation job is 45% complete ("progress": 45). The status could be "queued", "processing", or "completed", etc., and progress may be a percentage or other indicator of completion. Not all jobs will report a numeric progress – some may only update the status.

    Sample Response (Completed):

    Once the job status is "completed", the response may include the generated image data (similar format as the direct generate-image endpoint). In the example above, the data array contains bytes of a PNG image (137 80 78 71 ... are the signature bytes of a PNG file). You can then retrieve or save this image data as needed.

    Note: In many cases, you might not need to manually grab the raw image from the progress response. Instead, you would proceed to the minting step to get the final NFT metadata. The backend typically stores the generated image and prepares metadata when the job completes. The Progress endpoint is primarily for status updates; the final image and metadata are obtained via the minting endpoint next.

    NFT Mint Configuration/ metadata - POST /mint-nft

    Description: Finalizes the NFT creation by generating the metadata and preparing for minting. You call this after an image generation job is completed to get the NFT’s metadata (name, description, image URI, etc.) needed for on-chain minting. Think of this as retrieving the “mint package” for your NFT. Note: This endpoint does not perform the actual blockchain mint transaction itself; it returns the data that you or the ChainGPT service will use to mint the NFT on-chain.

    Headers:

    • Authorization: Bearer YOUR_API_KEY (required)

    • Content-Type: application/json (required)

    Request Body Parameters:

    Parameter

    Type

    Description

    collectionId

    string (required)

    The ID of the completed generation job you want to mint, as returned by generate-nft-queue. Ensure that the generation status is "completed" before calling this (you can check via the progress endpoint).

    name

    string (required)

    The desired name of the NFT. This will be stored in the token metadata as the title of the artwork.

    description

    string (required)

    A description for the NFT. This text can describe the artwork or provide context, and will be included in the metadata.

    symbol

    string (required)

    A short symbol or ticker for the NFT (or the collection). For example, "DRAGON" or "CGPT". This may be used as an identifier for the NFT collection or simply stored as part of the metadata.

    Sample Request:

    Sample Response:

    The response typically returns a JSON object representing the NFT metadata. In the example above, the response echoes the name and description you provided, an image field (in this case an IPFS URI pointing to the generated image), and possibly an attributes array if any attributes were added. The collectionId is included again for reference. A transaction field may also appear – for example, if the system automatically initiated an on-chain mint, this might contain a transaction hash; if not (as in this example), it may be null.

    Next Steps: Once you have the NFT metadata (especially the image URI and the metadata JSON URI if provided), you can proceed to mint the NFT on the blockchain. If ChainGPT’s service handles the minting for you, it might provide a transaction or update to indicate the NFT was minted. Otherwise, you can use the returned data along with the provided smart contract ABI and chain information to perform the mint. Typically, you would use a web3 library and call the contract’s mint function, providing the target wallet address (the same walletAddress used earlier) and a tokenURI that points to the metadata JSON. The mint-nft endpoint’s purpose is to prepare the off-chain metadata needed for the NFT, allowing you to review or edit it before performing the actual on-chain mint.


    Prompt Enhancement (POST /nft/enhancePrompt)

    This optional endpoint uses AI to enhance or refine a text prompt for better image generation results. It does not generate an image itself, but returns an improved prompt that you can then use with the image generation endpoints.

    Description: Takes a given prompt and returns a more detailed or refined version of that prompt. This can help yield higher-quality or more specific images from the models by ensuring the prompt is well-crafted. (For example, a short prompt "a futuristic city" might be expanded into a more vivid description.)

    Headers:

    • Authorization: Bearer YOUR_API_KEY (required)

    • Content-Type: application/json (required)

    Request Body:

    • prompt (string, required) – The original prompt text that you want to enhance/refine.

    Sample Request:

    Sample Response:

    The response contains an enhancedPrompt field with a more descriptive version of the input prompt. You can use this refined prompt in a subsequent image generation call to potentially get better results. Each call to prompt enhancement consumes a small amount of credits (see Pricing & Credits, typically 0.5 credits per enhancement).


    Supported Chains (GET /nft/get-chains)

    Use this endpoint to retrieve the list of blockchain networks supported by the AI NFT Generator for minting NFTs.

    Description: Returns an array of supported blockchains (networks) on which you can mint the generated NFTs. Each network entry includes its chainId and name. By default, only mainnet networks are returned; you can optionally include test networks.

    Headers:

    • Authorization: Bearer YOUR_API_KEY (required)

    Query Parameters:

    • testNet (boolean, optional) – If true, include testnet chains in the results. If omitted or false, only mainnet chains are listed.

    Sample Request:

    Sample Response:

    Each entry in the chains list provides a blockchain’s ID and a human-readable name, and often a network type (mainnet or testnet). Use the chainId values when calling the generation and minting endpoints (generate-nft-queue and mint-nft) to specify the target blockchain. For example, use chainId: 97 with a BSC Testnet wallet address, or chainId: 1 with an Ethereum address, etc..

    Note: Ensure the walletAddress you provide in the generation call is valid on the chosen chain. The ChainGPT NFT Generator supports multiple blockchains for minting, so choosing the correct chain ID and corresponding wallet is important.


    Contract ABI (GET /nft/abi)

    This endpoint provides the ABI (Application Binary Interface) of the ChainGPT NFT smart contract used for minting. Developers can use the ABI to interact with the NFT contract via web3 libraries.

    Description: Returns the ABI for the ChainGPT NFT Mint Factory smart contract. The ABI is a JSON array describing the contract’s functions and events. With this, you can programmatically call contract functions (like the mint function) or decode events when integrating on-chain.

    Headers:

    • Authorization: Bearer YOUR_API_KEY (required)

    Sample Request:

    Sample Response (truncated):

    The actual ABI JSON will include all the contract’s functions and events. The snippet above illustrates the general structure (e.g., a mint function that takes a recipient address and token URI, and an NFTMinted event). Using this ABI, you can integrate with the blockchain directly. For instance, after you obtain the NFT metadata via mint-nft, you could use the ABI with a web3 library (and the appropriate contract address for the selected chainId) to call the mint function on the contract, passing in the walletAddress (as the to address) and the token URI that points to the NFT’s metadata. This is useful for custom on-chain interactions if not handled automatically by the ChainGPT service.


    Supported Models & Parameters

    When generating images, choose the appropriate model and parameters for your use case. The table below summarizes the supported models and their capabilities:

    Model

    Base Resolution Range

    Max Upscaled Resolution

    Max Steps

    velogen

    512–768 px (e.g. 512×512, 768×512)

    Up to ~1920Ă—1920 px with 2Ă— enhance

    1–4 steps

    nebula_forge_xl

    768–1024 px (e.g. 1024×768)

    Up to ~1536Ă—1536 px when upscaled

    1–50 steps

    VisionaryForge

    768–1024 px (similar to above)

    Up to ~1536Ă—1536 px when upscaled

    1–50 steps

    Notes:

    • Base Resolution is the native size the model can generate without enhancement. Max Upscaled is the approximate maximum size using the enhance parameter ("1x" or "2x"). For example, VeloGen can generate up to ~768px natively, or up to ~1920px when enhanced twice. NebulaForge XL and VisionaryForge can handle up to 1024px natively, or ~1536px with upscaling. Keep the aspect ratio in mind; you can request landscape, portrait, or square dimensions as long as they fall within these ranges.

    • If you request an image size beyond a model’s base range without setting enhance, the API may automatically apply an enhancement/upscale if possible. However, it’s recommended to explicitly use the enhance parameter if you want a higher resolution output, to be clear about the intent.

    • The steps parameter controls the number of diffusion/refinement iterations. VeloGen is optimized for speed with only a few steps (up to 4). More powerful models like NebulaForge XL and VisionaryForge can run up to 50 steps for finer detail. Higher step counts can significantly improve image quality for those models, at the cost of longer generation time. (The DALL·E 3 model does not use a custom steps setting – it generates at a fixed quality per prompt).

    • Prompt Enhancement: If your initial prompt is short or not yielding the desired results, consider using the prompt enhancement endpoint before generation. The POST /nft/enhancePrompt call can provide a more detailed prompt, which can help ensure you get a good result on the first generation attempt. This can be especially useful when using the more expensive models or high step counts.


    Pricing & Credits

    The ChainGPT NFT Generator API uses a credit-based system. Each API call deducts a certain number of credits from your account. The cost depends on the model and options used. Below is a brief overview of credit costs per image (see the Pricing & Credits page for full details):

    • VeloGen, NebulaForge XL, VisionaryForge: 1 credit per image for base resolution generation. If you use the enhancement (enhance = "1x" or "2x" for higher resolution), it costs an additional 1 credit, for a total of 2 credits per image with upscale. (E.g. generating a simple image = 1 credit; generating with HD enhancement = 2 credits.)

    • Prompt Enhancement: ~0.5 credits per call. Enhancing a prompt via POST /nft/enhancePrompt deducts a small fraction of a credit (since it does not generate an image, just text).

    • Other Endpoints: Non-generative endpoints such as checking progress, retrieving supported chains, or fetching the contract ABI do not consume credits. The mint-nft endpoint for metadata preparation also does not charge credits (it assumes the generation was already paid for), aside from any separate blockchain transaction costs which are outside the scope of the API.

    • Extras: DALL·E 3 (Dale3) model: Higher cost due to external API usage. For a 1024Ă—1024 image at standard quality (no upscale), 4.75 credits~~~~ are charged. Enabling HD upscale ("2x") for a 1024px image doubles this to ~9.5 credits. For other resolutions, standard generation is ~9.5 credits and HD upscaled is ~14.25 credits per image. (In summary, DALL·E generations range roughly from 4.75 up to 14.25 credits each depending on size/quality.)

    Note: You must have sufficient credits in your ChainGPT account before calling these APIs. If your credits are exhausted or the API key has no credits, calls to generate images (or enhance prompts) will fail (typically with a 401 Unauthorized or an error message indicating insufficient credits). Be sure to top up credits via the ChainGPT web app as needed. Full pricing details and credit packages are available on the ChainGPT Pricing & Membership Plans page.

    Authorization: Bearer YOUR_API_KEY
     curl -X POST https://api.chaingpt.org/nft/generate-image \
      -H "Authorization: Bearer YOUR_API_KEY" \
      -H "Content-Type: application/json" \
      -d '{
        "prompt": "dragon",
        "model": "velogen",
        "enhance": "original",
        "steps": 3,
        "height": 512,
        "width": 512,
        "style": "cinematic",
        "traits": [
          {
            "trait_type": "Background",
            "value": [
              { "value": "Heaven", "ratio": 20 },
              { "value": "Hell", "ratio": 60 },
              { "value": "garden", "ratio": 20 }
            ]
          },
          {
            "trait_type": "contrast",
            "value": [
              { "value": "dark", "ratio": 20 },
              { "value": "light", "ratio": 80 }
            ]
          }
        ]
      }'
    {
      "data": [255, 216, 237, ...]
    }
    fs.writeFileSync("output.jpg", Buffer.from(response.data.data));
    curl -X POST "https://api.chaingpt.org/nft/generate-multiple-images" \
      -H "Authorization: Bearer YOUR_API_KEY" \
      -H "Content-Type: application/json" \
      -d '{
        "prompt": [
          "cars racing to the finish",
          "bot running in the jungle"
        ],
        "model": "velogen",
        "enhance": "1x",
        "steps": 2,
        "height": 512,
        "width": 512,
        "style": "cinematic",
        "image": "https://chaingpt.s3.dualstack.us-east-2.amazonaws.com/sdk/cgpt-bot.jpg",
        "isCharacterPreserve": true
      }'
    curl -X POST "https://api.chaingpt.org/nft/generate-nft-queue" \
         -H "Authorization: Bearer YOUR_API_KEY" \
         -H "Content-Type: application/json" \
         -d '{
               "walletAddress": "0xABC123...DEF",
               "prompt": "Futuristic city skyline at night, neon glow",
               "model": "nebula_forge_xl",
               "steps": 25,
               "height": 1024,
               "width": 1024,
               "enhance": "2x",
               "chainId": 56,
               "amount":1,
               "style": "cinematic",
                "traits": [
                  {
                    "trait_type": "Background",
                    "value": [
                      { "value": "Heaven", "ratio": 20 },
                      { "value": "Hell", "ratio": 60 },
                      { "value": "garden", "ratio": 20 }
                    ]
                  }
                  ]
             }'
    {
      "collectionId": "b8f86f05-5e8a-4f21-8c4a-xxxxxxxxxxxx",
      "status": "queued"
    }
    curl -X GET "https://api.chaingpt.org/nft/progress/b8f86f05-5e8a-4f21-8c4a-xxxxxxxxxxxx" \
         -H "Authorization: Bearer YOUR_API_KEY"
    {
      "collectionId": "b8f86f05-5e8a-4f21-8c4a-xxxxxxxxxxxx",
      "status": "processing",
      "progress": 45
    }
    {
      "statusCode":200,
       "message":"Request Successful",
       "data":{"images":["https://ipfs..../..1.png"],
       "generated":true}
    }
    curl -X POST "https://api.chaingpt.org/nft/mint-nft" \
         -H "Authorization: Bearer YOUR_API_KEY" \
         -H "Content-Type: application/json" \
         -d '{
               "collectionId": "b8f86f05-5e8a-4f21-8c4a-xxxxxxxxxxxx",
               "name": "Neon Skyline City",
               "description": "A futuristic city skyline at night, generated by AI.",
               "symbol": "NEON",
               "ids":[1,....,n]
             }'
    {
      "name": "Neon Skyline City",
      "description": "A futuristic city skyline at night, generated by AI.",
      "image": "ipfs://Qm...abcd",
      "attributes": [ /* ... if any attributes ... */ ],
      "collectionId": "b8f86f05-5e8a-4f21-8c4a-xxxxxxxxxxxx",
      "transaction": null
    }
    curl -X POST "https://api.chaingpt.org/nft/enhancePrompt" \
         -H "Authorization: Bearer YOUR_API_KEY" \
         -H "Content-Type: application/json" \
         -d '{
               "prompt": "a futuristic city"
             }'
    {
      "enhancedPrompt": "A sprawling futuristic cityscape at night, illuminated by neon lights and flying vehicles, with towering skyscrapers and advanced technology."
    }
    # Fetch only mainnet chains
    curl -X GET "https://api.chaingpt.org/nft/get-chains?testNet=false" \
         -H "Authorization: Bearer YOUR_API_KEY"
    {
      "chains": [
                {
                    "chainId": 56,
                    "chainName": "BNB Smart Chain",
                    "network": "bsc",
                    "networkType": "Mainnet"
                },
                {
                    "chainId": 204,
                    "chainName": "opBNB Mainnet",
                    "network": "opbnb",
                    "networkType": "Mainnet"
                },
                {
                    "chainId": 534352,
                    "chainName": "Scroll",
                    "network": "scroll",
                    "networkType": "Mainnet"
                },
                {
                    "chainId": 42161,
                    "chainName": "Arbitrum One",
                    "network": "arbitrum-one",
                    "networkType": "Mainnet"
                },
                {
                    "chainId": 5000,
                    "chainName": "Mantle",
                    "network": "mantle",
                    "networkType": "Mainnet"
                },
                {
                    "chainId": 1350216234,
                    "chainName": "SKALE | Titan AI Hub",
                    "network": "skale-titan",
                    "networkType": "Mainnet"
                },
                {
                    "chainId": 196,
                    "chainName": "X Layer",
                    "network": "X Layer",
                    "networkType": "Mainnet"
                },
                {
                    "chainId": 1116,
                    "chainName": "COREDAO",
                    "network": "COREDAO",
                    "networkType": "Mainnet"
                },
                {
                    "chainId": 1329,
                    "chainName": "Sei",
                    "network": "SEI",
                    "networkType": "Mainnet"
                },
                {
                    "chainId": 995,
                    "chainName": "5ire",
                    "network": "5ire",
                    "networkType": "Mainnet"
                },
                {
                    "chainId": 1,
                    "chainName": "Ethereum",
                    "network": "ethereum",
                    "networkType": "Mainnet"
                },
                {
                    "chainId": 137,
                    "chainName": "Polygon",
                    "network": "matic",
                    "networkType": "Mainnet"
                },
                {
                    "chainId": 43114,
                    "chainName": "Avalanche",
                    "network": "avalanche",
                    "networkType": "Mainnet"
                },
                {
                    "chainId": 199,
                    "chainName": "BTTC ",
                    "network": "BitTorrent Chain Mainnet",
                    "networkType": "Mainnet"
                },
                {
                    "chainId": 88,
                    "chainName": "Viction",
                    "network": "viction-mainnet",
                    "networkType": "Mainnet"
                },
                {
                    "chainId": 8453,
                    "chainName": "Base",
                    "network": "Base Mainnet",
                    "networkType": "Mainnet"
                },
                {
                    "chainId": 13371,
                    "chainName": "Immutable",
                    "network": "Immutable-mainnet",
                    "networkType": "Mainnet"
                },
                {
                    "chainId": 59144,
                    "chainName": "Linea",
                    "network": "Linea Mainnet",
                    "networkType": "Mainnet"
                },
                {
                    "chainId": 295,
                    "chainName": "Hedera",
                    "network": "hedera-mainnet",
                    "networkType": "Mainnet"
                },
                {
                    "chainId": 80094,
                    "chainName": "Bera Chain",
                    "network": "bera-mainnet",
                    "networkType": "Mainnet"
                },
                {
                    "chainId": 146,
                    "chainName": "Sonic",
                    "network": "sonic-mainnet",
                    "networkType": "Mainnet"
                },
                {
                    "chainId": 25,
                    "chainName": "Cronos",
                    "network": "cronos-mainnet",
                    "networkType": "Mainnet"
                }
            ]
    }
    curl -X GET "https://api.chaingpt.org/nft/abi" \
         -H "Authorization: Bearer YOUR_API_KEY"
    {
      "abi": [
        {
          "type": "function",
          "name": "mint",
          "inputs": [
            { "name": "to", "type": "address" },
            { "name": "tokenURI", "type": "string" }
          ],
          "outputs": [ /* ... */ ]
        },
        {
          "type": "event",
          "name": "NFTMinted",
          "inputs": [ /* ... */ ]
        }
        // ...other functions and events...
      ]
    }

    width

    integer (required)

    Output image width in pixels. Must meet the same constraints as height. (For a square image, use equal width and height, e.g. 512Ă—512 or 1024Ă—1024.)

    enhance

    string (optional)

    Upscaling option to improve image quality. Allowed values: "original" (no enhancement), "1x" (single enhancement), or "2x" (double enhancement). If omitted or set to "original", the image is generated at base resolution. Using "1x" or "2x" will upscale the image (up to the model’s enhanced max resolution, e.g. ~1280px or 1920px) at additional credit cost (see Pricing & Credits).

    style

    string (optional)

    If you include a style, the image will be generated according to the specified style. Available styles are listed below. (Listed Styles)

    traits

    Array (optional)

    Traits are an optional array of objects. If provided, images will be generated based on the specified trait ratios. For example, if the array includes two traits—Background with values Heaven (ratio: 20) and Hell (ratio: 60)—and you request 5 images, approximately 1 will use Heaven and 3 will use Hell background.You can adjust traits and ratios to guide image generation accordingly.

    image

    Url (optional)

    If you are using image-to-image, include the image URL in your API request with the key image.

    isCharacterPreserve

    Bool (optional)

    Tells the generator to preserve the main character’s identity and features from the reference image (image URL) while still applying the prompt.

    height

    integer (required)

    Desired image height in pixels. Must be within the model’s allowed range (e.g. up to 1024 for base generation on NebulaForge XL).

    width

    integer (required)

    Desired image width in pixels. Must be within the allowed range for the model (same constraints as height).

    enhance

    string (optional)

    Enhancement/upscaling option ("original" (default), "1x" or "2x") for higher resolution output. If provided, the image will be upscaled up to the model’s enhanced max resolution. If omitted, the image is generated at base resolution. (Using enhancement will consume additional credits).

    chainId

    integer (required)

    Blockchain network ID where the NFT will be minted. Use the /nft/get-chains endpoint to see supported chains and their IDs. For example: 1 for Ethereum, 56 for BSC Mainnet, 97 for BSC Testnet, etc..

    amount

    number (required)

    Number of NFTs to be created in the collection

    style

    string (optional)

    If you include a style, the image will be generated according to the specified style. Available styles are listed below. (Listed Styles)

    traits

    array (optional)

    TTraits are an optional array of objects. If provided, images will be generated based on the specified trait ratios. For example, if the array includes two traits—Background with values Heaven (ratio: 20) and Hell (ratio: 60)—and you request 5 images, approximately 1 will use Heaven and 3 will use Hell background.You can adjust traits and ratios to guide image generation accordingly.

    ids

    array (required)

    An array of ID lists, where each ID corresponds to a token minted from the collections.

    Dale3 (DALL·E 3)

    1024Ă—1024 px (fixed)

    N/A (no custom upscale)

    N/A (no step parameter)