# Generate a Bria image Source: https://apidoc.cometapi.com/api/image/bria/generate-image api/openapi/image/bria/post-generate-image.openapi.json POST /bria/text-to-image Use CometAPI Bria POST /bria/text-to-image to generate 1MP photorealistic images from text with enhancements and flexible aspect ratios. Generate commercial-safe images from a plain text prompt. For a first request on CometAPI, send `prompt`, keep `num_results` at `1`, and start with `aspect_ratio: "1:1"` unless you already know the final layout you need. ## Use this route when * You want a finished image in one call * You do not need masks, image inputs, or task polling * You want a photorealistic Bria path that is easier to operationalize through CometAPI ## Start with this request * Keep the prompt short and concrete * Use `num_results: 1` for your first request * Start with `aspect_ratio: "1:1"` unless the target layout is already fixed * Download returned URLs promptly if you need long retention ## Response behavior on CometAPI Bria's official docs describe a broader generation pipeline and discuss async status flows. On CometAPI, this route uses a simplified JSON request and returns a final `result` array immediately rather than a `request_id` plus `status_url`. CometAPI proxies Bria capability rather than mirroring Bria's public API field-for-field. Use the request and response shapes shown in this page's API reference and Playground as the source of truth for integration. # Generate Bria vector graphics Source: https://apidoc.cometapi.com/api/image/bria/generate-vector-graphics-base api/openapi/image/bria/post-generate-vector-graphics-base.openapi.json POST /bria/text-to-vector Use CometAPI POST /bria/text-to-vector to generate editable, scalable vector assets from text with Bria Base (Beta) for icons, logos, and illustrations. ## Overview Generate high-quality, editable vector graphic assets from text prompts. Ideal for creating scalable icons, logos, and illustrations using Bria's proprietary text-to-image foundation models. This interface is equivalent to `https://engine.prod.bria-api.com/v1/text-to-vector/base/3.2` For details, see the [Bria official documentation](https://docs.bria.ai/image-generation/v1-endpoints/text-to-vector-base). ## When to use it Use this endpoint when the final asset needs to remain editable or scalable, such as icons, simple illustrations, logos, and layout graphics. Use raster image generation instead when you need photorealistic detail or complex textures. ## First request Start with a short prompt that describes the object, style, and intended use. Keep the first request simple, then add brand, color, or composition constraints after you confirm the vector output is usable. ## Read the response The response returns vector output fields through the API playground. Persist the returned asset promptly if your workflow needs long-term storage or later editing. # Edit images with Bria Source: https://apidoc.cometapi.com/api/image/bria/image-editing api/openapi/image/bria/post-image-editing.openapi.json POST /bria/image/edit/{action} Use Bria Image Editing API via CometAPI to erase, gen_fill, expand, enhance, upscale, or replace backgrounds with POST /bria/image/edit/{action}. ## Overview Bria's Image Editing API provides a comprehensive suite of tools for manipulating and enhancing images. After a successful API call, use the returned `request_id` to query results via the [Query Status](/api/image/bria/query-status) endpoint. The `sync` parameter is fixed on this interface — you do not need to specify it. ### Supported operations | Operation | Description | Documentation | | --------------------- | -------------------------------- | ------------------------------------------------------------------------------------------ | | `erase` | Remove objects from images | [Bria Erase Docs](https://docs.bria.ai/image-editing/v2-endpoints/erase) | | `gen_fill` | Generative fill for masked areas | [Bria Gen Fill Docs](https://docs.bria.ai/image-editing/v2-endpoints/gen-fill) | | `expand` | Expand image canvas | [Bria Expand Docs](https://docs.bria.ai/image-editing/v2-endpoints/image-expansion) | | `enhance` | Enhance image quality | [Bria Enhance Docs](https://docs.bria.ai/image-editing/v2-endpoints/enhance) | | `increase_resolution` | Upscale image resolution | [Bria Upscale Docs](https://docs.bria.ai/image-editing/v2-endpoints/increase-resolution) | | `replace_background` | Replace image background | [Bria Background Docs](https://docs.bria.ai/image-editing/v2-endpoints/background-replace) | Please refer to the official documentation for the parameter list specific to each operation. # Get Bria request status Source: https://apidoc.cometapi.com/api/image/bria/query-status api/openapi/image/bria/get-query-status.openapi.json GET /bria/{request_id} Check Bria Image Editing progress with CometAPI Query Status API (GET /bria/{request_id}) for async image requests and results readiness. ## Overview Retrieve the status and result of an asynchronous [Edit images with Bria](/api/image/bria/image-editing) request by its `request_id`. This endpoint is only used for Bria Image Editing tasks. Use the `request_id` returned from the editing API call. # Generate a FLUX image Source: https://apidoc.cometapi.com/api/image/flux/flux-generate-image api/openapi/image/flux/post-flux-generate-image.openapi.json POST /flux/v1/{model} Submit FLUX.2 text-to-image and reference-image tasks through CometAPI's native BFL-compatible endpoint. ## Overview `POST /flux/v1/\{model\}` submits a native BFL-format image task. Store the top-level response `id`, then poll [`GET /flux/v1/get_result`](/api/image/flux/flux-query) with that task ID. The API playground includes text-to-image request examples for FLUX.2 Pro, Flex, and Max. Check the [Models page](/overview/models) or `/v1/models` for model IDs and account availability. ## Request fields Start with `prompt`, `width`, `height`, and `output_format`. You can also send `seed`; the completed result can report the seed used, but that field alone does not establish repeatable output. For reference-image editing, send a public HTTPS image URL in `input_image`. This field is supported for the three FLUX.2 models above. FLUX.2 Pro also accepts a second public HTTPS URL in `input_image_2`; include `input_image` whenever you send `input_image_2`. ## Submit and poll The create response can use `status: "processing"` while the task runs. Use its top-level `id` with the CometAPI result endpoint; clients should not depend on a response-supplied `polling_url`. Poll until the result endpoint returns `status: "Ready"`. Treat `Error`, `Failed`, `Failure`, `Task not found`, `Request Moderated`, and `Content Moderated` as failures. For other states, continue polling within your application's retry and timeout limits. When a task is ready, `result.sample` is a temporary image URL. Download or transfer it promptly; do not rely on a fixed lifetime. # Get a FLUX image result Source: https://apidoc.cometapi.com/api/image/flux/flux-query api/openapi/image/flux/get-flux-query.openapi.json GET /flux/v1/get_result Poll a native FLUX image task by its top-level ID and retrieve the generated image URL when its status is Ready. ## Overview Pass the top-level task `id` returned by `POST /flux/v1/\{model\}` as the `id` query parameter. Keep polling within a bounded client timeout until the task succeeds or fails. | Status | Client action | | ------------------------------- | ------------------------------------------------------------------- | | `Ready` | Read `result.sample`, then download or transfer the image promptly. | | `Error`, `Failed`, or `Failure` | Stop and surface the task error. | | `Task not found` | Stop; the ID is unknown or no longer available. | | `Request Moderated` | Stop; the request was rejected by moderation. | | `Content Moderated` | Stop; the generated content was rejected by moderation. | | Any other status | Continue polling until your client timeout is reached. | The successful result can include `sample`, `seed`, `prompt`, and `start_time`. Some fields can be omitted, so only require `result.sample` after the task is `Ready`. `result.sample` is temporary. Do not use a provider result URL as a durable application asset. # Generate images with Gemini Source: https://apidoc.cometapi.com/api/image/gemini/gemini-generates-image api/openapi/image/gemini/post-gemini-generates-image.openapi.json POST /v1beta/models/{model}:generateContent Generate images with Gemini models via CometAPI — supports 4K, multi-turn editing, up to 14 reference images, and Thinking. For step-by-step examples, see [Use Gemini image models](/api/image/gemini/generate-image-guide). Gemini image generation options can change as Google updates image models and `generateContent`. Check the [Gemini image generation documentation](https://ai.google.dev/gemini-api/docs/image-generation) for the latest complete parameter list and provider-specific behavior. `gemini-2.5-flash-image` is scheduled for shutdown by the provider on 2026-10-02. For new projects, use `gemini-3.1-flash-image-preview` or `gemini-3-pro-image-preview`. See Google's [deprecation schedule](https://ai.google.dev/gemini-api/docs/deprecations) for details. Gemini image responses can include intermediate image parts where `thought` is `true`. These are not the final output. When saving generated images, skip `thought: true` parts and use the last image part where `inlineData` exists and `thought` is not `true`. # Use Gemini image models Source: https://apidoc.cometapi.com/api/image/gemini/generate-image-guide Call Gemini image models (Nano Banana 2 / Pro) on CometAPI using the Google Gen AI SDK for text-to-image, image-to-image, and multi-image composition. This guide demonstrates how to use Gemini image models via CometAPI using the **Google Gen AI SDK**. It covers: * Text-to-image generation * Image-to-image editing * Multi-image composition * Saving generated images - **Base URL:** `https://api.cometapi.com` - Install the SDK: `pip install google-genai` (Python) or `npm install @google/genai` (Node.js) *** ## Setup Initialize the client with CometAPI's base URL: ```python Python theme={null} from google import genai from google.genai import types import os COMETAPI_KEY = os.environ["COMETAPI_KEY"] client = genai.Client( http_options={"api_version": "v1beta", "base_url": "https://api.cometapi.com"}, api_key=COMETAPI_KEY, ) ``` ```javascript Node.js theme={null} import { GoogleGenAI } from "@google/genai"; const COMETAPI_KEY = process.env.COMETAPI_KEY; const ai = new GoogleGenAI({ apiKey: COMETAPI_KEY, httpOptions: { apiVersion: "v1beta", baseUrl: "https://api.cometapi.com" }, }); ``` ```go Go theme={null} package main import ( "context" "os" "google.golang.org/genai" ) func main() { ctx := context.Background() apiKey := os.Getenv("COMETAPI_KEY") client, _ := genai.NewClient(ctx, &genai.ClientConfig{ APIKey: apiKey, Backend: genai.BackendGeminiAPI, HTTPOptions: genai.HTTPOptions{ BaseURL: "https://api.cometapi.com", }, }) // use client below... } ``` *** ## Text-to-image generation Generate an image from a text prompt and save it to a file. ```python Python theme={null} from google import genai from google.genai import types from PIL import Image import os client = genai.Client( http_options={"api_version": "v1beta", "base_url": "https://api.cometapi.com"}, api_key=os.environ.get("COMETAPI_KEY"), ) response = client.models.generate_content( model="gemini-3.1-flash-image-preview", contents="Create a picture of a nano banana dish in a fancy restaurant with a Gemini theme", config=types.GenerateContentConfig( response_modalities=["TEXT", "IMAGE"], ), ) final_image = None for part in response.parts: if getattr(part, "thought", False): continue if part.text is not None: print(part.text) elif part.inline_data is not None: final_image = part.as_image() if final_image: final_image.save("generated_image.png") print("Image saved to generated_image.png") ``` ```javascript Node.js theme={null} import { GoogleGenAI } from "@google/genai"; import * as fs from "fs"; const ai = new GoogleGenAI({ apiKey: process.env.COMETAPI_KEY, httpOptions: { apiVersion: "v1beta", baseUrl: "https://api.cometapi.com" }, }); const response = await ai.models.generateContent({ model: "gemini-3.1-flash-image-preview", contents: "Create a picture of a nano banana dish in a fancy restaurant with a Gemini theme", config: { responseModalities: ["TEXT", "IMAGE"] }, }); let finalImagePart; for (const part of response.candidates[0].content.parts) { if (part.thought === true) { continue; } if (part.text) { console.log(part.text); } if (part.inlineData) { finalImagePart = part; } } if (finalImagePart) { const buffer = Buffer.from(finalImagePart.inlineData.data, "base64"); fs.writeFileSync("generated_image.png", buffer); console.log("Image saved to generated_image.png"); } ``` ```bash Shell theme={null} curl -s -X POST \ "https://api.cometapi.com/v1beta/models/gemini-3.1-flash-image-preview:generateContent" \ -H "Authorization: Bearer $COMETAPI_KEY" \ -H "Content-Type: application/json" \ -d '{ "contents": [{ "parts": [{"text": "Create a picture of a nano banana dish in a fancy restaurant with a Gemini theme"}] }], "generationConfig": { "responseModalities": ["TEXT", "IMAGE"] } }' ``` **Save the final image part:** The image data is in `candidates[0].content.parts`, which can contain text and/or image parts. Gemini image models can also return intermediate thought parts before the final image, especially when you request both text and images or explicitly enable thinking output. Do not save the first `inlineData` blindly; skip parts where `thought` is `true`, then save the last remaining image part. Typical response with only the final image: ```json theme={null} { "candidates": [{ "content": { "parts": [ { "text": "Here is your image..." }, { "inlineData": { "mimeType": "image/png", "data": "" } } ] } }] } ``` Response with a text part, an intermediate thought image, and the final image: ```json theme={null} { "candidates": [{ "content": { "role": "model", "parts": [ { "text": "Here is your image..." }, { "inlineData": { "mimeType": "image/jpeg", "data": "" }, "thought": true }, { "inlineData": { "mimeType": "image/jpeg", "data": "" }, "thought": false, "thoughtSignature": "" } ] }, "finishReason": "STOP" }] } ``` Use this parsing rule for every Gemini image response: ```javascript theme={null} const imageParts = response.candidates[0].content.parts.filter( (part) => part.inlineData && part.thought !== true, ); const finalImagePart = imageParts.at(-1); ``` *** ## Image-to-image generation Upload an input image and transform it with a text prompt. ```python Python theme={null} from google import genai from google.genai import types from PIL import Image import os client = genai.Client( http_options={"api_version": "v1beta", "base_url": "https://api.cometapi.com"}, api_key=os.environ.get("COMETAPI_KEY"), ) # Load the source image source_image = Image.open("source.jpg") response = client.models.generate_content( model="gemini-3.1-flash-image-preview", contents=["Transform this into a watercolor painting", source_image], config=types.GenerateContentConfig( response_modalities=["TEXT", "IMAGE"], ), ) final_image = None for part in response.parts: if getattr(part, "thought", False): continue if part.text is not None: print(part.text) elif part.inline_data is not None: final_image = part.as_image() if final_image: final_image.save("watercolor_output.png") ``` ```javascript Node.js theme={null} import { GoogleGenAI } from "@google/genai"; import * as fs from "fs"; const ai = new GoogleGenAI({ apiKey: process.env.COMETAPI_KEY, httpOptions: { apiVersion: "v1beta", baseUrl: "https://api.cometapi.com" }, }); const imageData = fs.readFileSync("source.jpg").toString("base64"); const response = await ai.models.generateContent({ model: "gemini-3.1-flash-image-preview", contents: [ { text: "Transform this into a watercolor painting" }, { inlineData: { mimeType: "image/jpeg", data: imageData } }, ], config: { responseModalities: ["TEXT", "IMAGE"] }, }); const imageParts = response.candidates[0].content.parts.filter( (part) => part.inlineData && part.thought !== true, ); const finalImagePart = imageParts.at(-1); if (finalImagePart) { fs.writeFileSync("watercolor_output.png", Buffer.from(finalImagePart.inlineData.data, "base64")); } ``` ```bash Shell theme={null} curl -s -X POST \ "https://api.cometapi.com/v1beta/models/gemini-3.1-flash-image-preview:generateContent" \ -H "Authorization: Bearer $COMETAPI_KEY" \ -H "Content-Type: application/json" \ -d '{ "contents": [{ "role": "user", "parts": [ { "text": "Transform this into a watercolor painting" }, { "inline_data": { "mime_type": "image/jpeg", "data": "" } } ] }], "generationConfig": { "responseModalities": ["TEXT", "IMAGE"] } }' ``` * The Python SDK accepts `PIL.Image` objects directly — no manual Base64 encoding needed. * Do **not** include the `data:image/jpeg;base64,` prefix when passing raw Base64 strings. *** ## Multi-image composition Generate a new image from multiple input images. CometAPI supports two approaches: ### Method 1: Single collage image Combine multiple source images into one collage, then describe the desired output. Input collage example Generated output ```python Python theme={null} from google import genai from google.genai import types from PIL import Image import os client = genai.Client( http_options={"api_version": "v1beta", "base_url": "https://api.cometapi.com"}, api_key=os.environ.get("COMETAPI_KEY"), ) collage = Image.open("collage.jpg") response = client.models.generate_content( model="gemini-3.1-flash-image-preview", contents=[ "A model is posing and leaning against a pink BMW with a green alien keychain attached to a pink handbag, a pink parrot on her shoulder, and a pug wearing a pink collar and gold headphones", collage, ], config=types.GenerateContentConfig( response_modalities=["TEXT", "IMAGE"], ), ) final_image = None for part in response.parts: if getattr(part, "thought", False): continue if part.inline_data is not None: final_image = part.as_image() if final_image: final_image.save("composition_output.png") ``` ```bash Shell theme={null} curl -s -X POST \ "https://api.cometapi.com/v1beta/models/gemini-3.1-flash-image-preview:generateContent" \ -H "Authorization: Bearer $COMETAPI_KEY" \ -H "Content-Type: application/json" \ -d '{ "contents": [{ "role": "user", "parts": [ { "text": "A model is posing and leaning against a pink BMW with a green alien keychain attached to a pink handbag, a pink parrot on her shoulder, and a pug wearing a pink collar and gold headphones" }, { "inline_data": { "mime_type": "image/jpeg", "data": "" } } ] }], "generationConfig": { "responseModalities": ["TEXT", "IMAGE"] } }' ``` ### Method 2: Multiple separate images (up to 14) Pass multiple images directly. Gemini 3 models support up to 14 reference images (objects + characters): ```python Python theme={null} from google import genai from google.genai import types from PIL import Image import os client = genai.Client( http_options={"api_version": "v1beta", "base_url": "https://api.cometapi.com"}, api_key=os.environ.get("COMETAPI_KEY"), ) image1 = Image.open("image1.jpg") image2 = Image.open("image2.jpg") image3 = Image.open("image3.jpg") response = client.models.generate_content( model="gemini-3.1-flash-image-preview", contents=["Merge the three images", image1, image2, image3], config=types.GenerateContentConfig( response_modalities=["TEXT", "IMAGE"], ), ) final_image = None for part in response.parts: if getattr(part, "thought", False): continue if part.inline_data is not None: final_image = part.as_image() if final_image: final_image.save("merged_output.png") ``` ```bash Shell theme={null} curl -s -X POST \ "https://api.cometapi.com/v1beta/models/gemini-3.1-flash-image-preview:generateContent" \ -H "Authorization: Bearer $COMETAPI_KEY" \ -H "Content-Type: application/json" \ -d '{ "contents": [{ "role": "user", "parts": [ { "text": "Merge the three images" }, { "inline_data": { "mime_type": "image/jpeg", "data": "" } }, { "inline_data": { "mime_type": "image/jpeg", "data": "" } }, { "inline_data": { "mime_type": "image/jpeg", "data": "" } } ] }], "generationConfig": { "responseModalities": ["TEXT", "IMAGE"] } }' ``` Multi-image generation result *** ## 4K image generation Specify `image_config` with `aspect_ratio` and `image_size` for high-resolution output: ```python Python theme={null} from google import genai from google.genai import types import os client = genai.Client( http_options={"api_version": "v1beta", "base_url": "https://api.cometapi.com"}, api_key=os.environ.get("COMETAPI_KEY"), ) response = client.models.generate_content( model="gemini-3.1-flash-image-preview", contents="Da Vinci style anatomical sketch of a Monarch butterfly on textured parchment", config=types.GenerateContentConfig( response_modalities=["TEXT", "IMAGE"], image_config=types.ImageConfig( aspect_ratio="1:1", image_size="4K", ), ), ) final_image = None for part in response.parts: if getattr(part, "thought", False): continue if part.text is not None: print(part.text) elif image := part.as_image(): final_image = image if final_image: final_image.save("butterfly_4k.png") ``` ```javascript Node.js theme={null} import { GoogleGenAI } from "@google/genai"; import * as fs from "fs"; const ai = new GoogleGenAI({ apiKey: process.env.COMETAPI_KEY, httpOptions: { apiVersion: "v1beta", baseUrl: "https://api.cometapi.com" }, }); const response = await ai.models.generateContent({ model: "gemini-3.1-flash-image-preview", contents: "Da Vinci style anatomical sketch of a Monarch butterfly on textured parchment", config: { responseModalities: ["TEXT", "IMAGE"], imageConfig: { aspectRatio: "1:1", imageSize: "4K" }, }, }); const imageParts = response.candidates[0].content.parts.filter( (part) => part.inlineData && part.thought !== true, ); const finalImagePart = imageParts.at(-1); if (finalImagePart) { fs.writeFileSync("butterfly_4k.png", Buffer.from(finalImagePart.inlineData.data, "base64")); } ``` ```bash Shell theme={null} curl -s -X POST \ "https://api.cometapi.com/v1beta/models/gemini-3.1-flash-image-preview:generateContent" \ -H "Authorization: Bearer $COMETAPI_KEY" \ -H "Content-Type: application/json" \ -d '{ "contents": [{"parts": [{"text": "Da Vinci style anatomical sketch of a Monarch butterfly on textured parchment"}]}], "generationConfig": { "responseModalities": ["TEXT", "IMAGE"], "imageConfig": {"aspectRatio": "1:1", "imageSize": "4K"} } }' ``` For high-resolution requests, judge the output by the final non-thought image part. If your integration saves the first `inlineData` part, it may save an intermediate thought image that is lower resolution than the requested `imageSize`. *** ## Multi-turn image editing (chat) Use the SDK's chat feature to iteratively refine images: ```python Python theme={null} from google import genai from google.genai import types import os client = genai.Client( http_options={"api_version": "v1beta", "base_url": "https://api.cometapi.com"}, api_key=os.environ.get("COMETAPI_KEY"), ) chat = client.chats.create( model="gemini-3.1-flash-image-preview", config=types.GenerateContentConfig( response_modalities=["TEXT", "IMAGE"], ), ) ## First turn: Generate response = chat.send_message( "Create a vibrant infographic explaining photosynthesis as a recipe, styled like a colorful kids cookbook" ) final_image = None for part in response.parts: if getattr(part, "thought", False): continue if part.text is not None: print(part.text) elif image := part.as_image(): final_image = image if final_image: final_image.save("photosynthesis.png") ## Second turn: Refine response = chat.send_message("Update this infographic to be in Spanish. Do not change any other elements.") final_image = None for part in response.parts: if getattr(part, "thought", False): continue if part.text is not None: print(part.text) elif image := part.as_image(): final_image = image if final_image: final_image.save("photosynthesis_spanish.png") ``` ```javascript Node.js theme={null} import { GoogleGenAI } from "@google/genai"; import * as fs from "fs"; const ai = new GoogleGenAI({ apiKey: process.env.COMETAPI_KEY, httpOptions: { apiVersion: "v1beta", baseUrl: "https://api.cometapi.com" }, }); const chat = ai.chats.create({ model: "gemini-3.1-flash-image-preview", config: { responseModalities: ["TEXT", "IMAGE"] }, }); // First turn: generate const response1 = await chat.sendMessage( "Create a vibrant infographic explaining photosynthesis as a recipe, styled like a colorful kids cookbook" ); const imageParts1 = response1.candidates[0].content.parts.filter( (part) => part.inlineData && part.thought !== true, ); const finalImagePart1 = imageParts1.at(-1); if (finalImagePart1) { fs.writeFileSync("photosynthesis.png", Buffer.from(finalImagePart1.inlineData.data, "base64")); } // Second turn: refine const response2 = await chat.sendMessage( "Update this infographic to be in Spanish. Do not change any other elements." ); const imageParts2 = response2.candidates[0].content.parts.filter( (part) => part.inlineData && part.thought !== true, ); const finalImagePart2 = imageParts2.at(-1); if (finalImagePart2) { fs.writeFileSync("photosynthesis_spanish.png", Buffer.from(finalImagePart2.inlineData.data, "base64")); } ``` *** ## Tips Specify style keywords (e.g., "cyberpunk, film grain, low contrast"), aspect ratio, subject, background, lighting, and detail level. When using raw HTTP, do not include `data:image/png;base64,` prefix — use only the raw Base64 string. The Python SDK handles this automatically with `PIL.Image` objects. Set `"responseModalities"` to `["IMAGE"]` only to guarantee image output without text. Check whether your code saved an intermediate thought image. Gemini image responses may include image parts where `thought` is `true`; these are not the final output. Skip `thought: true` parts and save the last image part where `inlineData` exists and `thought` is not `true`. If you do not need text output, request `"responseModalities": ["IMAGE"]` to reduce mixed text/image response handling. For more details, see the [API Reference](/api/image/gemini/gemini-generates-image). **Official documentation:** [Nano Banana image generation](https://ai.google.dev/gemini-api/docs/image-generation) * [Gemini Image Understanding](https://ai.google.dev/gemini-api/docs/image-understanding) # Edit images with Grok Source: https://apidoc.cometapi.com/api/image/grok/image-editing api/openapi/image/grok/post-image-editing.openapi.json POST /v1/images/edits Edit one or more images with Grok by sending image URLs or data URIs in a JSON request. Use this route to edit one or more images with Grok image models. The request body uses `application/json`. ## Provide image input * Send exactly one of `image` or `images`. * Use `image` for one source image. * Use `images` for two or three source images. * In each image object, use `url` for a public URL or data URI. `image_url` is a compatibility alias for `url`. * Use `aspect_ratio` to control the output shape for multi-image edits. Choose a Grok image model ID from the [Models page](/overview/models). The API examples use `grok-imagine-image-quality`. Send Grok image edit requests as JSON. Multipart form data does not represent this request shape. The OpenAI SDK `images.edit()` method sends multipart form data. Use a direct HTTP request for Grok JSON image edits. For provider parameter details, see the [xAI image editing guide](https://docs.x.ai/developers/model-capabilities/images/editing). # Generate images with Grok Source: https://apidoc.cometapi.com/api/image/grok/image-generation api/openapi/image/grok/post-image-generation.openapi.json POST /v1/images/generations Generate Grok images with JSON requests, aspect ratio controls, resolution controls, and URL or Base64 output. Use this route to create images from text with Grok image models. The request body uses `application/json`. The request supports `model`, `prompt`, `n`, `aspect_ratio`, `resolution`, and `response_format`. ## Choose a model Choose a Grok image model ID from the [Models page](/overview/models). The API examples use `grok-imagine-image-quality`. ## Configure the output * Use `aspect_ratio` to select the output shape, or use `auto` to let the model select the shape. * Use `resolution` to request `1k` or `2k` output. * Use `n` to request up to 10 images. * Use `response_format` to return temporary URLs or Base64-encoded image data. For provider parameter details, see the [xAI image generation guide](https://docs.x.ai/developers/model-capabilities/images/generation). Download URL results after the request completes. Generated image URLs can expire. # Image generation and editing APIs Source: https://apidoc.cometapi.com/api/image/index Choose CometAPI image routes for OpenAI-compatible generation and edits, Gemini and Nano Banana, Midjourney, Flux, Bria, Replicate, and Seedream or SeedEdit workflows. Use CometAPI image model docs by choosing the request format that matches your workflow. OpenAI-compatible image endpoints cover common generation and editing flows; provider-specific pages cover task-based image systems. ## Choose an image API Generate images with an OpenAI-compatible request. Edit images with an OpenAI-compatible request. Generate or edit images with Gemini format. Submit and poll Midjourney image tasks. Generate Flux images through CometAPI. Use Bria image generation tools. Run Replicate-format image prediction requests. Create Seedream image generation requests. ## Generate an image Use an image-capable model ID from the [Models page](/overview/models) or the [model directory](https://www.cometapi.com/models/). The examples below call the OpenAI-compatible Create an image endpoint. These examples use the placeholder `your-image-model-id`. Replace it with an available image model ID from the [Models page](/overview/models) or [model directory](https://www.cometapi.com/models/) before you run the request. Open [Create an image](/api/image/openai/images) to use the playground and endpoint schema. ```python Python theme={null} import os import requests response = requests.post( "https://api.cometapi.com/v1/images/generations", headers={ "Authorization": "Bearer " + os.environ["COMETAPI_KEY"], "Content-Type": "application/json", }, json={ "model": "your-image-model-id", "prompt": "A clean product photo of a glass teapot on a white table", "size": "1024x1024", }, timeout=120, ) response.raise_for_status() result = response.json() print(result["data"][0].keys()) ``` ```javascript Node.js theme={null} const response = await fetch("https://api.cometapi.com/v1/images/generations", { method: "POST", headers: { Authorization: `Bearer ${process.env.COMETAPI_KEY}`, "Content-Type": "application/json", }, body: JSON.stringify({ model: "your-image-model-id", prompt: "A clean product photo of a glass teapot on a white table", size: "1024x1024", }), }); if (!response.ok) { throw new Error(await response.text()); } const result = await response.json(); console.log(Object.keys(result.data[0])); ``` ```bash cURL theme={null} curl https://api.cometapi.com/v1/images/generations \ -H "Authorization: Bearer $COMETAPI_KEY" \ -H "Content-Type: application/json" \ -d '{ "model": "your-image-model-id", "prompt": "A clean product photo of a glass teapot on a white table", "size": "1024x1024" }' ``` ## Response example A successful response can look like this. Depending on the selected model, each item can contain a base64 image or a result URL: ```json theme={null} { "created": 1779872000, "background": "opaque", "data": [ { "b64_json": "iVBORw0KGgo..." } ], "output_format": "png", "quality": "low", "size": "1024x1024", "usage": { "input_tokens": 19, "input_tokens_details": { "image_tokens": 0, "text_tokens": 19 }, "output_tokens": 196, "output_tokens_details": { "image_tokens": 196, "text_tokens": 0 }, "total_tokens": 215 } } ``` ## Example model records This example model catalog response shows the `/api/models` envelope and one image model record shape. It is not a complete model list. ```bash cURL theme={null} curl https://api.cometapi.com/api/models ``` ```json theme={null} { "success": true, "page": 1, "page_size": 20, "total": 302, "data": [ { "created": 1776391310, "id": "your-image-model-id", "code": "your-image-model-id", "provider": "ExampleProvider", "provider_code": "example", "name": "Example image model", "model_type": "image", "features": [ "text-to-image" ], "endpoints": "{\n \"openai-image\": {\n \"path\": \"/v1/images/generations\",\n \"method\": \"POST\"\n }\n}", "pricing": { "currency": "USD / M Tokens", "input": 4, "output": 24, "per_request": null, "per_second": null } } ] } ``` ## Common errors Choose an image-capable model from the [Models page](/overview/models). Use a size that the selected image endpoint accepts. Download generated assets before provider links expire. Use image URLs or smaller files instead of large base64 payloads. Check both `b64_json` and `url` fields because output shape can differ by model. ## Error codes and retry strategy Do not retry until the prompt, size, or image input is fixed. Do not retry until the API key is present and valid. Check the base URL, path, and model ID before retrying. Reduce upload size before retrying. Retry with exponential backoff and reduce concurrency. Retry with backoff for transient provider or service errors. For implementation patterns, see [Error codes and retry strategy](/guides/error-codes-and-retry-strategy) and [Rate limits and concurrency](/guides/rate-limits-and-concurrency). ## Pricing and model directory Read how CometAPI exposes model IDs in the docs. Browse model availability and capabilities. Check pricing before you call a model. # Expand an image with Kling Source: https://apidoc.cometapi.com/api/image/kling/image-expansion api/openapi/image/kling/post-image-expansion.openapi.json POST /kling/v1/images/editing/expand Use Kling Image Expansion API via CometAPI to expand images beyond their original borders with controllable outpainting. Use this endpoint to outpaint an image beyond its original borders when you need more canvas around the source content. ## How the expansion ratios work * Each ratio is measured against the original width or height * The combined expanded canvas must still stay within Kling's documented area limits * Start with small values such as `0.1` on each side before attempting larger expansions ## Request flow * Send all four ratio fields, using `0` for any side you do not want to expand * Save the returned `task_id` * Poll the matching Kling image query path until the task reaches a terminal state For the complete parameter reference, see the [official Kling documentation](https://kling.ai/document-api/api/image/common/outpainting). # Generate images with Kling Source: https://apidoc.cometapi.com/api/image/kling/image-generation api/openapi/image/kling/post-image-generation.openapi.json POST /kling/v1/images/generations Generate images with Kling via CometAPI: POST /kling/v1/images/generations supports prompt-driven image creation and image-reference generation. ## Image generation For the complete parameter reference, see the [official Kling documentation](https://kling.ai/document-api/api/image/3-0-omni/image-generation). Use this endpoint to create still images through Kling's image generation API. It supports text-only requests and image-reference requests through the same async task flow. ## First request Start with `model_name: kling-v3`, `prompt`, `n`, and `aspect_ratio`. Add reference images, fidelity controls, or advanced fields only after the first request returns a usable task. Omitting `model_name` uses a legacy compatibility default, so send `kling-v3` explicitly for new integrations. ## Read the response Save the returned `task_id`, then poll the matching Kling image query route until `task_status` reaches a terminal state. If your workflow needs durable storage, copy the final asset into your own storage layer after generation completes. # Generate a Kling image from multiple images Source: https://apidoc.cometapi.com/api/image/kling/multi-image-to-image api/openapi/image/kling/post-multi-image-to-image.openapi.json POST /kling/v1/images/multi-image2image Use CometAPI's Kling Multi-Image to Image endpoint to generate a new image from subject, scene, and style image references. Use this endpoint when you want Kling to generate one image from multiple subject references plus optional scene or style references. ## Before you call it * Provide 1 to 4 images in `subject_image_list` * Use `model_name: kling-v2-1` for new requests * Add `scene_image` or `style_image` only when the core subject composition already works * Treat this as an async generation route and save the returned task id ## Task flow Send the subject image list and prompt, then store the returned task id. Poll the returned task with the matching Kling image query path until the task reaches a terminal state. Save the generated image into your own storage if you need durable access. For the complete parameter reference, see the [official Kling documentation](https://kling.ai/document-api/api/image/2-1/multi-image-to-image). # Create a Kling Omni image task Source: https://apidoc.cometapi.com/api/image/kling/omni-image api/openapi/image/kling/post-omni-image.openapi.json POST /kling/v1/images/omni-image Use CometAPI POST /kling/v1/images/omni-image to create Kling Omni Image tasks with prompt and reference-image inputs. Use this endpoint to create an asynchronous Kling Omni Image task through CometAPI. The create request returns a `task_id`; use [Get a Kling Omni image task](/api/image/kling/omni-image-query) to poll the task until the generated image URLs are available. For the complete provider parameter reference, see the [Kling Image O1 documentation](https://kling.ai/document-api/api/image/o1/image-generation). ## Choose the request shape * Single-image generation: send `prompt`, `image_list`, `resolution`, `result_type: single`, `n`, and `aspect_ratio` * Watermarked output: add `watermark_info.enabled: true` when you need a watermarked result URL in the query response * Model ID: omit `model_name` to use the route default, or send a tested Omni Image model ID such as `kling-image-o1` or `kling-v3-omni` Reference images use `image_list` items with an `image` field. The prompt can cite them by index, such as `<<>>` for the first item and `<<>>` for the second item. ## Task flow Submit `POST /kling/v1/images/omni-image` and store the returned `data.task_id`. Poll [GET /kling/v1/images/omni-image/](/api/image/kling/omni-image-query) until `data.task_status` is `succeed` or `failed`. When the task succeeds, copy `data.task_result.images[].url` into your own storage if you need durable access. For the full response schema and task-status details, see [Get a Kling Omni image task](/api/image/kling/omni-image-query). The following request queries one task once: ```bash theme={null} curl "https://api.cometapi.com/kling/v1/images/omni-image/" \ -H "Authorization: Bearer $COMETAPI_KEY" ``` ## Result fields Successful query responses return generated images under `data.task_result.images`. Each item can include: | Field | Description | | --------------- | --------------------------------------------------------- | | `index` | Position of the generated image in the task result. | | `url` | Generated image URL. | | `watermark_url` | Watermarked image URL when watermark output is requested. | Generated asset URLs can expire or be cleared by the provider service. Store the finished images in your own storage layer when your workflow needs long retention. # Get a Kling Omni image task Source: https://apidoc.cometapi.com/api/image/kling/omni-image-query api/openapi/image/kling/get-omni-image.openapi.json GET /kling/v1/images/omni-image/{task_id} Use CometAPI GET /kling/v1/images/omni-image/{task_id} to poll Kling Omni Image task status and retrieve generated image URLs. Use this endpoint after you [create a Kling Omni image task](/api/image/kling/omni-image). Pass the `data.task_id` returned by the create request and poll until `data.task_status` is `succeed` or `failed`. The CometAPI public query route is `GET /kling/v1/images/omni-image/{task_id}`. Do not use `GET /v1/images/omni-image`; that route is not a CometAPI public query endpoint for Kling Omni Image tasks. ## Polling behavior * Use the same CometAPI account that created the task * Poll every 20-30 seconds until `task_status` is `succeed` or `failed` * Read generated image URLs from `data.task_result.images` when the task succeeds * Store finished images in your own storage if you need durable access Tasks from another account, expired records, or unknown IDs return `task_not_exist`. ## Result fields Successful query responses return generated images under `data.task_result.images`. Each item can include: | Field | Description | | --------------- | --------------------------------------------------------- | | `index` | Position of the generated image in the task result. | | `url` | Generated image URL. | | `watermark_url` | Watermarked image URL when watermark output is requested. | Generated asset URLs can expire or be cleared by the provider service. Store the finished images in your own storage layer when your workflow needs long retention. # Create a Kling virtual try-on Source: https://apidoc.cometapi.com/api/image/kling/virtual-try-on api/openapi/image/kling/post-virtual-try-on.openapi.json POST /kling/v1/images/kolors-virtual-try-on Use CometAPI Kling Virtual Try-On API to create a try-on image from a person image and clothing image. Use this endpoint to generate a virtual try-on image from one person image and one garment image. ## Before you call it * Provide one `human_image` and one `cloth_image` * Start with `kolors-virtual-try-on-v1` or `kolors-virtual-try-on-v1-5` * Use clean clothing product shots or white-background garment images for the first test ## Task flow Send the person image and clothing image, then save the returned task id. Poll the matching Kling image query path until the task reaches a terminal state and returns the rendered image. Save the finished image into your own storage if the try-on result needs longer retention. For the complete parameter reference, see the [official Kling documentation](https://kling.ai/document-api/api/image/virtual-try-on). # Create a Midjourney action task Source: https://apidoc.cometapi.com/api/image/midjourney/action api/openapi/image/midjourney/post-action.openapi.json POST /mj/submit/action Use CometAPI POST /mj/submit/action to apply Midjourney actions—upscale, variation, reroll, zoom, and more—on generated images. Use this endpoint after a Midjourney task returns action buttons. It starts a new downstream task such as upscale, variation, reroll, zoom, or pan. ## You need two values * `taskId` from the original or most recent Midjourney task * `customId` from the latest `buttons` array returned by [Fetch Single Task](./task-fetching-api/fetch-single-task) `customId` is not stable. Never hardcode it. Always read it from the latest polling response. ## Common actions * `U1` to `U4`: upscale one image from the grid * `V1` to `V4`: generate variations from one image position * Reroll: regenerate the full grid * Zoom and Pan: extend the existing composition ## After you submit an action Send `taskId` and `customId`, then store the new returned task id. Query [Fetch Single Task](./task-fetching-api/fetch-single-task) again until the action finishes. If the new task reaches `MODAL`, continue with [Modal](./modal) to supply the extra input. # Create a Midjourney blend task Source: https://apidoc.cometapi.com/api/image/midjourney/blend api/openapi/image/midjourney/post-blend.openapi.json POST /mj/submit/blend Submit images to the POST /mj/submit/blend endpoint to blend one or more inputs into a new Midjourney-style image with CometAPI. Use this endpoint to blend 2 to 5 source images into a new Midjourney composition. It is a direct entry point and does not require a prior imagine task. ## Before you call it * Prepare 2 to 5 source images * Keep the first test small and skip extra account-routing options unless you need them * Save the returned task id, because blending is still asynchronous ## Task flow Send the source images through the blend endpoint and store the returned task id. Use [Fetch Single Task](./task-fetching-api/fetch-single-task) until the task reaches a terminal state. When action buttons appear, use [Action](./action) for upscale, variation, or other follow-up steps. # Describe an image with Midjourney Source: https://apidoc.cometapi.com/api/image/midjourney/describe api/openapi/image/midjourney/post-describe.openapi.json POST /mj/submit/describe Use CometAPI POST /mj/submit/describe to extract an initial Midjourney prompt from an uploaded image for fast remixing and iteration. Use this endpoint to extract Midjourney-style prompt suggestions from an input image. ## What this route is good for * Turning an image into prompt candidates you can remix * Extracting a visual direction before you start a fresh imagine task * Building a faster authoring loop when you do not want to write the first prompt from scratch ## Task flow Upload or reference the image you want Midjourney to describe and store the returned task id. Use [Fetch Single Task](./task-fetching-api/fetch-single-task) until the task completes and returns prompt-like output. Take the prompt candidate that fits your intent and continue with [Imagine](./imagine) for a fresh generation pass. # Create a Midjourney imagine task Source: https://apidoc.cometapi.com/api/image/midjourney/imagine api/openapi/image/midjourney/post-imagine.openapi.json POST /mj/submit/imagine Use POST /mj/submit/imagine in CometAPI to create Midjourney imagine tasks with full Discord params, track task_id status, and enable image-to-video motion effects. Use this endpoint to start the main Midjourney workflow. Every later step, including upscale, variation, and custom zoom, begins with a successful imagine task. ## What the first response gives you * `result` is the task id you will poll next * `code` can still be a success code even when it is not HTTP-style `200` ## Core workflow Send the prompt and store the returned task id. Use [Fetch Single Task](./task-fetching-api/fetch-single-task) until the task reaches `SUCCESS`, `MODAL`, or `FAILURE`. When buttons appear, use [Action](./action) for upscale, variation, reroll, zoom, and similar follow-up operations. ## Optional video prompt pattern If you want motion from a source image, add an image URL plus Midjourney video flags in the prompt, such as `--video` and `--motion`. # Start with Midjourney API Source: https://apidoc.cometapi.com/api/image/midjourney/midjourney-api-quick-start Quick start for Midjourney API on CometAPI: submit /mj/submit/imagine, poll /mj/task/{id}/fetch, then use /mj/submit/action and modal buttons. ## Understand the core concept The MidJourney API **simulates Discord button interactions**. Unlike typical REST APIs, it works as a **state machine** where each operation returns new buttons for the next step. ### The 4 core APIs | API | Purpose | When to Use | | ---------------------------------------------------------------------------------------- | ------------------------------------------ | ------------------------------------ | | [`POST /mj/submit/imagine`](/api/image/midjourney/imagine) | Text-to-image generation | Starting point for all workflows | | [`GET /mj/task/\{id\}/fetch`](/api/image/midjourney/task-fetching-api/fetch-single-task) | Query task status & get buttons | After every submit (poll until done) | | [`POST /mj/submit/action`](/api/image/midjourney/action) | Click a button (upscale, vary, zoom, etc.) | When you want to operate on an image | | [`POST /mj/submit/modal`](/api/image/midjourney/modal) | Submit additional input | Only when status is `MODAL` | *** ## Complete workflow diagram ``` ┌─────────────────────────────────────────────────────────────────────────────┐ │ MIDJOURNEY API WORKFLOW │ └─────────────────────────────────────────────────────────────────────────────┘ ┌──────────────────┐ │ POST /submit/ │ ← Step 1: Submit prompt, get task_id │ imagine │ └────────┬─────────┘ │ Returns: { "result": "task_id_1" } ▼ ┌──────────────────┐ │ GET /task/{id}/ │ ← Step 2: Poll until status = "SUCCESS" │ fetch │ └────────┬─────────┘ │ Returns: imageUrl + buttons[] (U1,U2,U3,U4,V1,V2,V3,V4,🔄) ▼ ┌──────────────────┐ │ POST /submit/ │ ← Step 3: Click a button using customId │ action │ └────────┬─────────┘ │ Returns: { "result": "task_id_2" } ▼ ┌──────────────────┐ │ GET /task/{id}/ │ ← Step 4: Poll the new task │ fetch │ └────────┬─────────┘ │ ├─── status = "SUCCESS" → Done! Get imageUrl │ └─── status = "MODAL" → Need additional input (see Step 5) │ ▼ ┌──────────────────┐ │ POST /submit/ │ ← Step 5: Submit mask/prompt for special operations │ modal │ └────────┬─────────┘ │ Returns: { "result": "task_id_3" } ▼ ┌──────────────────┐ │ GET /task/{id}/ │ ← Step 6: Poll until SUCCESS │ fetch │ └──────────────────┘ ``` *** ## Key concept: Buttons and customId Every successful task returns a `buttons` array. Each button has a `customId` that you use to trigger the next action. **Example response from `/mj/task/\{id\}/fetch`:** ```json theme={null} { "status": "SUCCESS", "imageUrl": "https://api.cometapi.com/mj/image/xxx", "buttons": [ { "customId": "MJ::JOB::upsample::1::abc123", "label": "U1" }, { "customId": "MJ::JOB::upsample::2::abc123", "label": "U2" }, { "customId": "MJ::JOB::variation::1::abc123", "label": "V1" }, { "customId": "MJ::JOB::reroll::0::abc123", "emoji": "🔄" } ] } ``` `customId` is not a fixed value. It changes for every task. Always get it from the `buttons` array. *** ## Button reference by stage ### After IMAGINE (4-grid image) These buttons are returned when your initial image generation completes: | Button | customId Pattern | Action | Result | | ------ | ------------------------------- | -------------------- | --------------------- | | U1-U4 | `MJ::JOB::upsample::1::xxx` | Upscale single image | High-res single image | | V1-V4 | `MJ::JOB::variation::1::xxx` | Generate variations | New 4-grid | | 🔄 | `MJ::JOB::reroll::0::xxx::SOLO` | Regenerate all | New 4-grid | ### After UPSCALE (single image) After upscaling, you get access to editing tools: | Label | Needs Modal? | | --------------------------------- | -------------- | | Upscale (Subtle) / Upscale (2x) | ❌ No | | Upscale (Creative) / Upscale (4x) | ❌ No | | Vary (Subtle) 🪄 | ❌ No | | Vary (Strong) 🪄 | ❌ No | | Vary (Region) 🖌️ | ✅ Yes (mask) | | Zoom Out 2x / 1.5x 🔍 | ❌ No | | Custom Zoom 🔍 | ✅ Yes (prompt) | | ⬅️➡️⬆️⬇️ Pan | ❌ No | | Animate 🎞️ | ❌ No | | 🔄 Reroll | ❌ No | > **Note:** Button labels and `customId` formats may vary depending on the MJ version specified in your prompt (e.g., `--v 6.1` vs `--v 5.2`). Always read buttons from the API response. Inpaint (Vary Region) button only appears after Upscale. *** ## Complete example: Generate and upscale ### Step 1: Submit imagine request ```bash theme={null} curl -X POST 'https://api.cometapi.com/mj/submit/imagine' \ -H "Authorization: Bearer $COMETAPI_KEY" \ -H 'Content-Type: application/json' \ -d '{ "botType": "MID_JOURNEY", "prompt": "a cute cat --v 6.1", "accountFilter": { "modes": ["FAST"] } }' ``` **Response:** ```json theme={null} { "code": 1, "result": "1768464763141701" } ``` ### Step 2: Poll task status ```bash theme={null} curl -X GET 'https://api.cometapi.com/mj/task/1768464763141701/fetch' \ -H "Authorization: Bearer $COMETAPI_KEY" ``` **Response (when complete):** ```json theme={null} { "status": "SUCCESS", "imageUrl": "https://api.cometapi.com/mj/image/1768464763141701", "buttons": [ { "customId": "MJ::JOB::upsample::1::5f20922e-xxx", "label": "U1" }, { "customId": "MJ::JOB::upsample::2::5f20922e-xxx", "label": "U2" }, ... ] } ``` ### Step 3: Click U1 to upscale ```bash theme={null} curl -X POST 'https://api.cometapi.com/mj/submit/action' \ -H "Authorization: Bearer $COMETAPI_KEY" \ -H 'Content-Type: application/json' \ -d '{ "taskId": "1768464763141701", "customId": "MJ::JOB::upsample::1::5f20922e-xxx" }' ``` **Response:** ```json theme={null} { "code": 1, "result": "1768464800000000" } ``` ### Step 4: Poll new task and get result ```bash theme={null} curl -X GET 'https://api.cometapi.com/mj/task/1768464800000000/fetch' \ -H "Authorization: Bearer $COMETAPI_KEY" ``` *** ## When is Modal required? When you call [`/mj/submit/action`](/api/image/midjourney/action) and the task status becomes `MODAL` instead of `SUCCESS`, you must call [`/mj/submit/modal`](/api/image/midjourney/modal) to provide additional input. ### Confirmed Modal operations | Operation | Button | What to Submit | | ----------- | -------------- | --------------------------------------- | | Inpaint | Vary (Region) | `maskBase64` (PNG mask) + `prompt` | | Custom Zoom | 🔍 Custom Zoom | `prompt` (e.g., "your prompt --zoom 2") | **Example: Inpaint Flow** Start the Inpaint action: ```bash theme={null} curl -X POST 'https://api.cometapi.com/mj/submit/action' \ -H "Authorization: Bearer $COMETAPI_KEY" \ -H 'Content-Type: application/json' \ -d '{"taskId": "", "customId": "", "enableRemix": true}' ``` Query the new task once. A `MODAL` status means that the task needs the mask and prompt: ```bash theme={null} curl -X GET 'https://api.cometapi.com/mj/task//fetch' \ -H "Authorization: Bearer $COMETAPI_KEY" ``` Submit the mask and prompt through the Modal API: ```bash theme={null} curl -X POST 'https://api.cometapi.com/mj/submit/modal' \ -H "Authorization: Bearer $COMETAPI_KEY" \ -H 'Content-Type: application/json' \ -d '{ "taskId": "", "prompt": "replace with golden crown", "maskBase64": "data:image/png;base64," }' ``` *** ## Speed mode selection Add speed prefix to the path: | Mode | Path Prefix | Example | | ----- | ----------- | ----------------------------- | | Fast | `/mj-fast` | `/mj-fast/mj/submit/imagine` | | Turbo | `/mj-turbo` | `/mj-turbo/mj/submit/imagine` | | Relax | (default) | `/mj/submit/imagine` | *** ## Other entry points These APIs are **independent entry points** that don't follow the imagine → action flow: | API | Purpose | | -------------------------------------------------------------- | -------------------------- | | [`POST /mj/submit/blend`](/api/image/midjourney/blend) | Blend 2-5 images into one | | [`POST /mj/submit/describe`](/api/image/midjourney/describe) | Generate prompt from image | | [`POST /mj/submit/video`](/api/image/midjourney/submit-video) | Convert image to video | | [`POST /mj/submit/edits`](/api/image/midjourney/submit-editor) | Edit image with mask | *** ## Troubleshooting tips Based on the API design and workflow, here are common issues you may encounter: | Problem | Likely Cause | Solution | | ------------------------------- | ----------------------------------- | ------------------------------------------------------------------------------------------------------------------------------ | | Can't find Vary (Region) button | Looking at 4-grid image | Upscale first (click U1-U4), then check buttons | | Task status stuck at `MODAL` | Operation requires additional input | Call [`/mj/submit/modal`](/api/image/midjourney/modal) with required data | | `customId` not working | Using outdated or hardcoded value | Always get fresh `customId` from [`/mj/task/\{id\}/fetch`](/api/image/midjourney/task-fetching-api/fetch-single-task) response | | Empty `buttons` array | Task still in progress | Wait for `status: "SUCCESS"` before accessing buttons | # Create a Midjourney modal task Source: https://apidoc.cometapi.com/api/image/midjourney/modal api/openapi/image/midjourney/post-modal.openapi.json POST /mj/submit/modal Use POST /mj/submit/modal to submit Midjourney modal output from zoom or area redesign and continue the next image editing step in CometAPI. ## Overview Submit additional input when an [Action](/api/image/midjourney/action) task returns `status: "MODAL"`. This is required for operations that need extra data, such as inpainting masks or custom zoom prompts. ### When to use | Operation | What to Submit | | --------------------------- | --------------------------------------- | | **Vary (Region) / Inpaint** | `maskBase64` (PNG mask) + `prompt` | | **Custom Zoom** | `prompt` (e.g., "your prompt --zoom 2") | For a complete inpaint flow example, see [Start with Midjourney API](/api/image/midjourney/midjourney-api-quick-start). # Create a Midjourney editor task Source: https://apidoc.cometapi.com/api/image/midjourney/submit-editor api/openapi/image/midjourney/post-submit-editor.openapi.json POST /mj/submit/edits Use CometAPI Submit Editor API (POST /mj/submit/edits) to edit Midjourney images with maskBase64, prompts, optional originals, and transparent edits. Use this endpoint to edit a Midjourney image with a mask, or to generate a transparent-background result from a prompt plus source image. ## Two common modes * Masked edit: send `maskBase64` plus `prompt`, and optionally the original `image` * Transparent drawing: send `image` plus `prompt` when you want a transparent-background result without a separate mask ## Task flow Choose the editing mode, send the prompt and source data, then store the returned task id. Use [Fetch Single Task](./task-fetching-api/fetch-single-task) until the task reaches a terminal state. Use the final asset directly, or trigger [Action](./action) when the edited result exposes follow-up buttons. # Create a Midjourney video task Source: https://apidoc.cometapi.com/api/image/midjourney/submit-video api/openapi/image/midjourney/post-submit-video.openapi.json POST /mj/submit/video Use POST /mj/submit/video in CometAPI to submit a Midjourney video job, set parameters, and track processing for generated video output. Use this endpoint to turn a Midjourney image result into a short video render. ## Before you call it * Start from a finished Midjourney image result or a supported image URL * Treat the returned task id as the start of an async workflow * Expect the finished asset to arrive through the same polling endpoint used by other Midjourney tasks ## Task flow Start the render and store the returned task id. Use [Fetch Single Task](./task-fetching-api/fetch-single-task) until the task reaches a terminal state and exposes the final video URL. Move the finished video into your own storage if you need stable retention beyond the provider delivery URL. # Fetch a Midjourney task Source: https://apidoc.cometapi.com/api/image/midjourney/task-fetching-api/fetch-single-task api/openapi/image/midjourney/task-fetching-api/get-fetch-single-task.openapi.json GET /mj/task/{id}/fetch Use CometAPI GET /mj/task/{id}/fetch to retrieve a single Midjourney task status quickly and reliably for monitoring and result polling. Use this endpoint after every Midjourney submit call. It is the main polling endpoint for imagine, action, modal, blend, and editor workflows. ## Check these fields first * `status` for the overall task state * `progress` for the current completion signal * `imageUrl` or `videoUrl` when the asset is ready * `buttons` for the next available `customId` values ## Polling rules * Keep polling until the task reaches `SUCCESS`, `MODAL`, or `FAILURE` * Treat the `buttons` array as the source of truth for follow-up actions * Use `imageUrl` when you need the finished grid or upscale result # List Midjourney tasks Source: https://apidoc.cometapi.com/api/image/midjourney/task-fetching-api/list-by-condition api/openapi/image/midjourney/task-fetching-api/post-list-by-condition.openapi.json POST /mj/task/list-by-condition POST /mj/task/list-by-condition lists Midjourney tasks by filters to fetch status for one or multiple jobs, including progress and results. Use this endpoint when you need to retrieve a batch of Midjourney tasks instead of polling one task id at a time. ## When to use it * You are tracking many Midjourney tasks together * You want to filter by task state, submission window, or other server-side conditions * You need a dashboard or reconciliation job instead of an interactive single-task poll ## Query pattern For one active task, prefer [Fetch Single Task](./fetch-single-task), because it is simpler and faster. Send your filter conditions through this endpoint when you need to inspect multiple Midjourney tasks in one request. When the batch result shows tasks that need deeper inspection or continuation, switch back to [Fetch Single Task](./fetch-single-task) and [Action](../action). Use this route for monitoring and reconciliation jobs; use [Fetch Single Task](./fetch-single-task) for the main interactive polling path. # Create image edit Source: https://apidoc.cometapi.com/api/image/openai/image-editing api/openapi/image/openai/post-image-editing.openapi.json POST /v1/images/edits Use POST /v1/images/edits in CometAPI to edit images with multipart uploads, masks, GPT image models, and encoded image output controls. Use this route to edit existing images with OpenAI-compatible multipart uploads on CometAPI. ## Use this route when * You already have a source image and want a prompt-driven edit * You may need a mask for targeted changes * You can handle multipart file upload instead of a plain JSON request ## Safe first request * Start with one PNG or JPG file * Skip the mask until the base edit flow works * Use `model: "gpt-image-2"` for GPT image edit requests on this route * Use one short instruction that asks for one visible change * Read the edited result from `data[0].b64_json` * Set `output_format: "jpeg"` when you want a JPEG payload * Expect longer latency than plain image generation ## Model behavior * GPT image edit models on this route return inline base64 image data * `output_format` controls the encoded image type inside `b64_json` * `response_format` only matters when a model supports URL output * `qwen-image-edit` follows provider-specific edit behavior behind the same CometAPI route # Retrieve an image generation task Source: https://apidoc.cometapi.com/api/image/openai/image-generation-task api/openapi/image/openai/get-image-generation-task.openapi.json GET /v1/images/generations/{task_id} Use CometAPI GET /v1/images/generations/{task_id} to poll an async OpenAI-compatible image generation task and retrieve final image data. Use this endpoint after you create an image with `POST /v1/images/generations` and `async: true`. The create request returns `data.task_id`, and this endpoint returns the task state plus final image data when the task succeeds. ## Poll an image task Send `POST /v1/images/generations` with `async: true`, then store `data.task_id`. Call this endpoint with the stored task ID until `data.status` is `success` or `failure`. When `data.status` is `success`, read the first item in `data.data`. Depending on the selected model, the item can include `b64_json`, `url`, or `revised_prompt`. ## Status values * `pending`: The task is queued or generating. * `success`: The task finished and `data.data` contains the generated image data. * `failure`: The task failed. Check `data.fail_reason` when it is returned. # Create an image Source: https://apidoc.cometapi.com/api/image/openai/images api/openapi/image/openai/post-images.openapi.json POST /v1/images/generations Use CometAPI POST /v1/images/generations to create images with OpenAI-compatible image models and model-specific controls. Use this route to create images from text with OpenAI-compatible request shapes on CometAPI. ## Official reference * Read the [OpenAI image generation guide](https://developers.openai.com/api/docs/guides/image-generation) before you rely on model-specific controls such as `background`, `output_compression`, streaming, or future GPT image options. * Use the [OpenAI Create image reference](https://developers.openai.com/api/reference/resources/images/methods/generate) for the current parameter list. ## Choose a model first * Use a GPT image model such as `gpt-image-2` for text-to-image requests with controls like `output_format`, `quality`, or `background` * Use `qwen-image` when you need that provider specifically, but keep `n` at 1 * Pick a current image model ID from the [Models page](/overview/models) ## Safe first request * Start with `gpt-image-2` * Keep `size` at `1024x1024` * GPT image models return base64-encoded image data in `b64_json`; decode it to save the image file * Add `output_format` only when you need a specific encoded image type such as `jpeg` * Check the OpenAI image generation guide before you add `background`, `output_compression`, or streaming * Use one prompt and one output image before you add batch generation or style tuning ## Run an async image task Use `async: true` for long-running image jobs when your client prefers a submit-and-poll flow instead of holding one HTTP connection open. The create request returns `data.task_id`. Poll [Retrieve an image generation task](/api/image/openai/image-generation-task) until `data.status` is `success` or `failure`. The `async` field is a CometAPI extension for this route, not an OpenAI parameter. OpenAI documents `stream` and `partial_images` for GPT image models. CometAPI asynchronous task mode returns JSON task metadata and uses polling. Use async task mode with these documented model IDs: `gpt-image-2` and `doubao-seedream-4-0-250828`. For other image models, use synchronous generation or streaming unless async task support is documented for that model. When a request includes both `async: true` and `stream: true`, async task mode takes precedence. The create request returns JSON task metadata instead of an SSE stream. ## Model-specific request behavior * `response_format` applies to DALL·E models only; GPT image models return base64 data and ignore it * GPT image models use GPT-only controls such as `output_format`, `quality`, `background`, and `output_compression` * Follow the OpenAI image generation guide for the latest model-specific options * `qwen-image` does not support `n > 1` Generated images must comply with provider usage policies. Do not send illegal, violent, pornographic, or copyright-infringing prompts. # Create a Replicate prediction Source: https://apidoc.cometapi.com/api/image/replicate/create-predictions-general api/openapi/image/replicate/post-create-predictions-general.openapi.json POST /replicate/v1/models/{models}/predictions POST /replicate/v1/models/{models}/predictions creates FLUX images via Replicate format on CometAPI, with aspect ratio, quality, output format, and input tuning. Use this route to start a Replicate-style prediction on CometAPI and get back a prediction id for later polling. ## First request checklist * Put every model parameter inside the `input` object * Start with `black-forest-labs/flux-schnell` for the quickest first request * Keep the first request text-only unless you specifically need `input_image` or `input_images` * Save the returned prediction `id` for status checks ## Task flow Submit the path model id and the `input` object through this endpoint. Save the returned `id`, because you need it for later polling. Continue with [Get a Replicate prediction](./replicate-query) until `output` is populated or an error appears. # Get a Replicate prediction Source: https://apidoc.cometapi.com/api/image/replicate/replicate-query api/openapi/image/replicate/get-replicate-query.openapi.json GET /replicate/v1/predictions/{id} Query GET /replicate/v1/predictions/{id} to fetch Replicate prediction details and real-time progress by task ID for image generation workflows. Use this endpoint after you already have a Replicate prediction id. It reports the current task state and returns output URLs when the prediction completes. ## Check these fields first * `status` to see whether the prediction is still running or already finished * `output` for generated asset URLs * `error` for provider-side failures * `metrics` when you need execution timing or image-count details ## Polling pattern Start with [Create a Replicate prediction](./create-predictions-general). Keep querying until `status` becomes terminal and `output` is either populated or a provider error is returned. Treat returned asset URLs as delivery URLs and move them into your own storage if you need long retention. # Create a Seedream image task Source: https://apidoc.cometapi.com/api/image/seededit-seedream/bytedance-image-generation api/openapi/image/seededit-seedream/post-bytedance-image-generation.openapi.json POST /v1/images/generations Submit an asynchronous Seedream image task through CometAPI and store the returned task ID for polling. Use `POST /v1/images/generations` with `async: true` to submit a Seedream image task without holding the HTTP connection open. This asynchronous workflow applies to these model IDs: | Model | Model ID | | ----------------- | ---------------------------- | | Seedream 4.0 | `doubao-seedream-4-0-250828` | | Seedream 4.5 | `doubao-seedream-4-5-251128` | | Seedream 5.0 Lite | `doubao-seedream-5-0-260128` | | Seedream 5.0 Pro | `seedream-5-0-pro-260628` | For account availability, see the [Models page](/overview/models) or query `/v1/models`. For provider parameter details, see the BytePlus [image generation API](https://docs.byteplus.com/en/docs/ModelArk/1541523) and [Seedream 4.0-5.0 tutorial](https://docs.byteplus.com/en/docs/ModelArk/1824121). ## Submit the task Send `model`, `prompt`, and `async: true`. The example also requests a `2K` URL response with `watermark: false`. Size support varies by model ID, so use a size supported by the selected model. The create response returns `data.task_id`, `data.status`, and an empty `data.data` array while the task is pending. Store `data.task_id`; do not use the top-level response code as the task identifier. ## Poll the task Pass the stored task ID to [Retrieve a Seedream image task](/api/image/seededit-seedream/bytedance-image-generation-task). Continue polling while `data.status` is `pending`. Stop when it becomes `success` or `failure`. ## Read the image URL When a task succeeds, read `data.data[0].url` from parsed JSON. In shell, `jq -r '.data.data[0].url'` preserves special characters in the complete URL. Download or transfer the image promptly. The URL is temporary; this documentation does not assume a fixed lifetime. # Retrieve a Seedream image task Source: https://apidoc.cometapi.com/api/image/seededit-seedream/bytedance-image-generation-task api/openapi/image/seededit-seedream/get-bytedance-image-generation-task.openapi.json GET /v1/images/generations/{task_id} Use CometAPI GET /v1/images/generations/{task_id} to poll an async Seedream image generation task and retrieve final image data. Use this endpoint after you create a Seedream image with `POST /v1/images/generations` and `async: true`. The create request returns `data.task_id`, and this endpoint returns the task state plus final image data when the task succeeds. This workflow supports `doubao-seedream-4-0-250828`, `doubao-seedream-4-5-251128`, `doubao-seedream-5-0-260128`, and `seedream-5-0-pro-260628`. Check the [Models page](/overview/models) or `/v1/models` for account availability. ## Poll a Seedream image task Send `POST /v1/images/generations` with `async: true`, then store `data.task_id`. Call this endpoint with the stored task ID until `data.status` is `success` or `failure`. When `data.status` is `success`, read `data.data[0].url`. Other result fields, including `b64_json` and `revised_prompt`, can be empty in the URL workflow. Download or transfer the returned image promptly. The result URL is temporary; do not rely on a fixed lifetime. ## Status values * `pending`: The task is queued or generating. * `success`: The task finished and `data.data` contains the generated image data. * `failure`: The task failed. Check `data.fail_reason` when it is returned. # Create a Message Source: https://apidoc.cometapi.com/api/text/anthropic-messages api/openapi/text/post-anthropic-messages.openapi.json POST /v1/messages Use the Anthropic Messages API through CometAPI to call Claude models with adaptive thinking, prompt caching, tool use, web search, streaming, and effort control. CometAPI supports the Anthropic Messages API natively, giving you direct access to Claude models with Anthropic-specific features. Use this endpoint for Claude capabilities like adaptive thinking, prompt caching, and effort control. Use the official [Anthropic Messages API reference](https://platform.claude.com/docs/en/api/messages) as the authoritative source for the complete parameter list, response schema, and Claude-specific behavior. This CometAPI page explains how to send that request shape through CometAPI. Anthropic request parameters and response fields can change as Claude features evolve. Check the [Anthropic Messages API documentation](https://platform.claude.com/docs/en/api/messages) for the latest complete parameter list and provider-specific behavior. Many newer Claude models reject non-default `temperature`, `top_p`, and `top_k` values on the Messages API. Omit these sampling fields unless you have verified support for the selected model. If a model returns an unsupported or deprecated-parameter error, remove the field from the request. Both `x-api-key` and `Authorization: Bearer` headers are supported for authentication. The official Anthropic SDKs use `x-api-key` by default. ## Quick start To use the official Anthropic SDK with CometAPI, set the base URL: ```python Python theme={null} import os import anthropic client = anthropic.Anthropic( base_url="https://api.cometapi.com", api_key=os.environ["COMETAPI_KEY"], ) message = client.messages.create( model="claude-sonnet-5", max_tokens=1024, messages=[{"role": "user", "content": "Hello!"}], ) print(message.content[0].text) ``` ```javascript JavaScript theme={null} import Anthropic from "@anthropic-ai/sdk"; const client = new Anthropic({ apiKey: process.env.COMETAPI_KEY, baseURL: "https://api.cometapi.com", }); const message = await client.messages.create({ model: "claude-sonnet-5", max_tokens: 1024, messages: [{ role: "user", content: "Hello!" }], }); console.log(message.content[0].text); ``` ## Control adaptive thinking Use adaptive thinking with `output_config.effort` to control how much work Claude applies to a response. Newer Claude models reject the legacy manual thinking shape `thinking={"type": "enabled", "budget_tokens": ...}`. ```python theme={null} message = client.messages.create( model="claude-sonnet-5", max_tokens=4096, thinking={"type": "adaptive"}, output_config={"effort": "xhigh"}, messages=[ { "role": "user", "content": "Analyze the trade-offs between a monolithic architecture and microservices for a small engineering team.", } ], ) for block in message.content: if block.type == "text": print(block.text) ``` Thinking tokens count toward your `max_tokens` limit. Set `max_tokens` high enough for both thinking and the final answer when you use higher effort levels. *** ## Cache prompts To reduce latency and cost on subsequent requests, cache large system prompts or conversation prefixes. Add `cache_control` to content blocks that should be cached: ```python theme={null} message = client.messages.create( model="claude-sonnet-5", max_tokens=1024, system=[ { "type": "text", "text": "You are an expert code reviewer. [Long detailed instructions...]", "cache_control": {"type": "ephemeral"}, } ], messages=[{"role": "user", "content": "Review this code..."}], ) ``` Cache usage is reported in the response `usage` field: * `cache_creation_input_tokens` — tokens written to cache (billed at a higher rate) * `cache_read_input_tokens` — tokens read from cache (billed at a reduced rate) Prompt caching requires a minimum of **1,024 tokens** in the cached content block. Content shorter than this will not be cached. *** ## Stream responses To stream responses using Server-Sent Events (SSE), set `stream: true`. Events arrive in this order: 1. `message_start` — contains the message metadata and initial usage 2. `content_block_start` — marks the beginning of each content block 3. `content_block_delta` — incremental text chunks (`text_delta`) 4. `content_block_stop` — marks the end of each content block 5. `message_delta` — final `stop_reason` and complete `usage` 6. `message_stop` — signals the end of the stream ```python theme={null} with client.messages.stream( model="claude-sonnet-5", max_tokens=256, messages=[{"role": "user", "content": "Hello"}], ) as stream: for text in stream.text_stream: print(text, end="") ``` *** ## Control effort To control how much effort Claude puts into generating a response, use `output_config.effort`: ```python theme={null} message = client.messages.create( model="claude-sonnet-5", max_tokens=4096, messages=[ {"role": "user", "content": "Summarize this briefly."} ], output_config={"effort": "low"}, # "low", "medium", "high", "xhigh", or "max" ) ``` *** ## Use server tools Claude supports server-side tools that run on Anthropic's infrastructure: Fetch and analyze content from URLs: ```python theme={null} message = client.messages.create( model="claude-sonnet-5", max_tokens=1024, messages=[ {"role": "user", "content": "Analyze the content at https://arxiv.org/abs/1512.03385"} ], tools=[ {"type": "web_fetch_20250910", "name": "web_fetch", "max_uses": 5} ], ) ``` Search the web for real-time information: ```python theme={null} message = client.messages.create( model="claude-sonnet-5", max_tokens=1024, messages=[ {"role": "user", "content": "What are the latest developments in AI?"} ], tools=[ {"type": "web_search_20250305", "name": "web_search", "max_uses": 5} ], ) ``` *** ## Response example A typical response from CometAPI's Anthropic endpoint: ```json theme={null} { "id": "msg_bdrk_01UjHdmSztrL7QYYm7CKBDFB", "type": "message", "role": "assistant", "content": [ { "type": "text", "text": "Hello!" } ], "model": "claude-sonnet-5", "stop_reason": "end_turn", "stop_sequence": null, "usage": { "input_tokens": 19, "cache_creation_input_tokens": 0, "cache_read_input_tokens": 0, "cache_creation": { "ephemeral_5m_input_tokens": 0, "ephemeral_1h_input_tokens": 0 }, "output_tokens": 4 } } ``` *** ## Compare with OpenAI-compatible endpoint | Feature | Anthropic Messages (`/v1/messages`) | OpenAI-Compatible (`/v1/chat/completions`) | | ----------------- | ------------------------------------------------------------- | ------------------------------------------ | | Adaptive thinking | `thinking` with `type: "adaptive"` and `output_config.effort` | Not available | | Prompt caching | `cache_control` on content blocks | Not available | | Effort control | `output_config.effort` | Not available | | Web fetch/search | Server tools (`web_fetch`, `web_search`) | Not available | | Auth header | `x-api-key` or `Bearer` | `Bearer` only | | Response format | Anthropic format (`content` blocks) | OpenAI format (`choices`, `message`) | | Models | Claude only | Multi-provider (GPT, Claude, Gemini, etc.) | # Create a chat completion Source: https://apidoc.cometapi.com/api/text/chat api/openapi/text/post-chat.openapi.json POST /v1/chat/completions Use CometAPI POST /v1/chat/completions to send multi-message conversations to chat models with streaming, temperature, and max_tokens controls. CometAPI routes Chat Completions to multiple providers — including OpenAI, Claude, and Gemini — through a single OpenAI-compatible interface. Switch between models by changing the `model` parameter; most OpenAI-compatible SDKs work by setting `base_url` to `https://api.cometapi.com/v1`. Request parameters and response fields can vary significantly between model providers. Check the official documentation for the provider behind the model you use whenever you need the complete parameter list or provider-specific behavior. For example, `reasoning_effort` only applies to reasoning models (o-series, GPT-5.1+), and some models do not support `logprobs` or `n` > 1. For OpenAI Pro models, o-series reasoning models, and Codex models, use the [Responses](/api/text/responses) endpoint instead. These model families have more complete support on the Responses API. *** ## Message roles | Role | Description | | ----------- | ----------------------------------------------------------------------------------------------------------------- | | `system` | Sets the assistant's behavior and personality. Placed at the start of the conversation. | | `developer` | Replaces `system` for newer models (o1+). Provides instructions the model should follow regardless of user input. | | `user` | Messages from the end user. | | `assistant` | Previous model responses, used to maintain conversation history. | | `tool` | Results from tool/function calls. Must include `tool_call_id` matching the original tool call. | For newer models (GPT-4.1, GPT-5 series, o-series), prefer `developer` over `system` for instruction messages. Both work, but `developer` provides stronger instruction-following behavior. *** ## Send multimodal input Many models support images and audio alongside text. To send multimodal messages, use the array format for `content`: ```json theme={null} { "role": "user", "content": [ {"type": "text", "text": "Describe this image"}, { "type": "image_url", "image_url": { "url": "https://example.com/image.png", "detail": "high" } } ] } ``` The `detail` parameter controls image analysis depth: * `low` — faster, uses fewer tokens (fixed cost) * `high` — detailed analysis, more tokens consumed * `auto` — the model decides (default) *** ## Stream responses To receive incremental output, set `stream` to `true`. The response is delivered as **Server-Sent Events (SSE)**, where each event contains a `chat.completion.chunk` object: ``` data: {"id":"chatcmpl-xxx","object":"chat.completion.chunk","choices":[{"index":0,"delta":{"role":"assistant"},"finish_reason":null}]} data: {"id":"chatcmpl-xxx","object":"chat.completion.chunk","choices":[{"index":0,"delta":{"content":"Hello"},"finish_reason":null}]} data: {"id":"chatcmpl-xxx","object":"chat.completion.chunk","choices":[{"index":0,"delta":{"content":"!"},"finish_reason":null}]} data: {"id":"chatcmpl-xxx","object":"chat.completion.chunk","choices":[{"index":0,"delta":{},"finish_reason":"stop"}]} data: [DONE] ``` To include token usage statistics in streaming responses, set `stream_options.include_usage` to `true`. The usage data appears in the final chunk before `[DONE]`. *** ## Request structured output To force the model to return valid JSON matching a specific schema, use `response_format`: ```json JSON Schema Mode theme={null} { "response_format": { "type": "json_schema", "json_schema": { "name": "result", "strict": true, "schema": { "type": "object", "properties": { "answer": {"type": "string"}, "confidence": {"type": "number"} }, "required": ["answer", "confidence"], "additionalProperties": false } } } } ``` ```json JSON Object Mode theme={null} { "response_format": {"type": "json_object"} } ``` JSON Schema mode (`json_schema`) guarantees the output matches your schema exactly. JSON Object mode (`json_object`) only guarantees valid JSON — the structure is not enforced. *** ## Call tools and functions To enable the model to call external functions, provide tool definitions: ```json theme={null} { "tools": [ { "type": "function", "function": { "name": "get_weather", "description": "Get current weather for a city", "parameters": { "type": "object", "properties": { "location": {"type": "string", "description": "City name"} }, "required": ["location"] } } } ], "tool_choice": "auto" } ``` When the model decides to call a tool, the response will have `finish_reason: "tool_calls"` and the `message.tool_calls` array will contain the function name and arguments. You then execute the function and send the result back as a `tool` message with the matching `tool_call_id`. *** ## Cross-provider notes | Parameter | OpenAI GPT | Claude (via compat) | Gemini (via compat) | | ------------------ | ------------------ | ------------------- | ------------------------------------ | | `temperature` | 0–2 | 0–1 | 0–2 | | `top_p` | 0–1 | 0–1 | 0–1 | | `n` | 1–128 | 1 only | 1–8 | | `stop` | Up to 4 | Up to 4 | Up to 5 | | `tools` | ✅ | ✅ | ✅ | | `response_format` | ✅ | ✅ (json\_schema) | ✅ | | `logprobs` | ✅ | ❌ | ❌ | | `reasoning_effort` | o-series, GPT-5.1+ | ❌ | ❌ (use `thinking` for Gemini native) | * **`max_tokens`** — The legacy parameter. Works with most models but is deprecated for newer OpenAI models. * **`max_completion_tokens`** — The recommended parameter for GPT-4.1, GPT-5 series, and o-series models. Required for reasoning models as it includes both output tokens and reasoning tokens. CometAPI automatically handles the mapping when routing to different providers. * **`system`** — The traditional instruction role. Works with all models. * **`developer`** — Introduced with o1 models. Provides stronger instruction-following for newer models. Falls back to `system` behavior on older models. Use `developer` for new projects targeting GPT-4.1+ or o-series models. *** ## FAQ ### How to handle rate limits? When encountering `429 Too Many Requests`, implement exponential backoff: ```python theme={null} import os import time import random from openai import OpenAI, RateLimitError client = OpenAI( base_url="https://api.cometapi.com/v1", api_key=os.environ["COMETAPI_KEY"], ) def chat_with_retry(messages, max_retries=3): for i in range(max_retries): try: return client.chat.completions.create( model="gpt-5.6-sol", messages=messages, ) except RateLimitError: if i < max_retries - 1: wait_time = (2 ** i) + random.random() time.sleep(wait_time) else: raise ``` ### How to maintain conversation context? Include the full conversation history in the `messages` array: ```python theme={null} messages = [ {"role": "developer", "content": "You are a helpful assistant."}, {"role": "user", "content": "What is Python?"}, {"role": "assistant", "content": "Python is a high-level programming language..."}, {"role": "user", "content": "What are its main advantages?"}, ] ``` ### What does `finish_reason` mean? | Value | Meaning | | ---------------- | ------------------------------------------------------ | | `stop` | Natural completion or hit a stop sequence. | | `length` | Reached `max_tokens` or `max_completion_tokens` limit. | | `tool_calls` | The model invoked one or more tool/function calls. | | `content_filter` | Output was filtered due to content policy. | ### How to control costs? 1. Use `max_completion_tokens` to cap output length. 2. Use `gpt-5.6-terra` for a balance of intelligence and cost, or `gpt-5.6-luna` for efficient, high-volume workloads. 3. Keep prompts concise — avoid redundant context. 4. Monitor token usage in the `usage` response field. # Generate content Source: https://apidoc.cometapi.com/api/text/gemini-generating-content api/openapi/text/post-gemini-generating-content.openapi.json POST /v1beta/models/{model}:{operator} Use the Gemini native API format through CometAPI for text generation, multimodal input, reasoning, function calling, Google Search grounding, JSON mode, and streaming. CometAPI supports the Gemini native API format, giving you full access to Gemini-specific features like thinking control, Google Search grounding, native image generation modalities, and more. Use this endpoint when you need capabilities not available through the [OpenAI-compatible chat endpoint](/api/text/chat). Use Google's official [GenerateContent API reference](https://ai.google.dev/api/generate-content) as the authoritative source for the complete request fields, response schema, and Gemini model-specific behavior. This CometAPI page explains how to send that native request shape through CometAPI. Gemini request parameters and response fields can change as Google updates the native API. Check the [Gemini text generation documentation](https://ai.google.dev/gemini-api/docs/text-generation) for the latest complete parameter list and provider-specific behavior. Both `x-goog-api-key` and `Authorization: Bearer` headers are supported for authentication. ## Quick start To use any Gemini SDK or HTTP client with CometAPI, replace the base URL and API key: | Setting | Google Default | CometAPI | | -------- | ----------------------------------- | ------------------ | | Base URL | `generativelanguage.googleapis.com` | `api.cometapi.com` | | API key | `$GEMINI_API_KEY` | `$COMETAPI_KEY` | ## Send video input Gemini `generateContent` accepts video as a content part. Choose the input shape based on where the video is stored: | Video source | Request part | Use when | | ---------------- | ------------------ | --------------------------------------------------------------------------------------- | | Local video file | `inlineData` | The video is small enough to send as base64 in the JSON request. | | Public video URL | `fileData.fileUri` | The video is available through a public HTTPS URL that does not require authentication. | For REST and curl requests, use Gemini's camelCase field names such as `inlineData.mimeType` and `fileData.fileUri`. Do not send URL media as `file_data.file_uri`. This example sends inline MP4 data. Replace `` with the Base64 content of your video: ```sh theme={null} curl -X POST \ "https://api.cometapi.com/v1beta/models/gemini-3.5-flash:generateContent" \ -H "Content-Type: application/json" \ -H "x-goog-api-key: $COMETAPI_KEY" \ --data-binary @- <<'EOF' { "contents": [ { "role": "user", "parts": [ { "inlineData": { "mimeType": "video/mp4", "data": "" } }, { "text": "Analyze this video and list the key scenes." } ] } ], "generationConfig": { "maxOutputTokens": 512, "thinkingConfig": {"thinkingLevel": "MINIMAL"} } } EOF ``` This example sends a public MP4 URL with `fileData.fileUri`: ```sh theme={null} curl -X POST \ "https://api.cometapi.com/v1beta/models/gemini-3.5-flash:generateContent" \ -H "Content-Type: application/json" \ -H "x-goog-api-key: $COMETAPI_KEY" \ --data-binary @- <<'EOF' { "contents": [ { "role": "user", "parts": [ { "fileData": { "mimeType": "video/mp4", "fileUri": "https://your-video-host.example.com/source.mp4" } }, { "text": "Analyze this video and list the key scenes." } ] } ], "generationConfig": { "maxOutputTokens": 512, "thinkingConfig": {"thinkingLevel": "MINIMAL"} } } EOF ``` CometAPI does not recommend a separate Gemini Files API upload flow for this endpoint. Send media in the `generateContent` request itself with `inlineData` or `fileData.fileUri`. ## Configure thinking (reasoning) Gemini models can perform internal reasoning before generating a response. The control method depends on the model generation. Gemini 3 models use `thinkingLevel` to control reasoning depth. Available levels: `MINIMAL`, `LOW`, `MEDIUM`, `HIGH`. Use `gemini-3-flash-preview` as the default example model unless you specifically need a different Gemini 3 variant. ```sh theme={null} curl "https://api.cometapi.com/v1beta/models/gemini-3-flash-preview:generateContent" \ -H "Content-Type: application/json" \ -H "x-goog-api-key: $COMETAPI_KEY" \ -d '{ "contents": [{"parts": [{"text": "Explain quantum physics simply."}]}], "generationConfig": { "thinkingConfig": {"thinkingLevel": "LOW"} } }' ``` Gemini 2.5 models use `thinkingBudget` for fine-grained token-level control: * `0` — disable thinking * `-1` — dynamic (model decides, default) * `> 0` — specific token budget (e.g., `1024`, `2048`) ```sh theme={null} curl "https://api.cometapi.com/v1beta/models/gemini-2.5-flash:generateContent" \ -H "Content-Type: application/json" \ -H "x-goog-api-key: $COMETAPI_KEY" \ -d '{ "contents": [{"parts": [{"text": "Solve this logic puzzle step by step."}]}], "generationConfig": { "thinkingConfig": {"thinkingBudget": 2048} } }' ``` Using `thinkingLevel` with Gemini 2.5 models (or `thinkingBudget` with Gemini 3 models) may cause errors. Use the correct parameter for your model version. *** ## Stream responses To receive Server-Sent Events as the model generates content, use `streamGenerateContent?alt=sse` as the operator. Each SSE event contains a `data:` line with a JSON `GenerateContentResponse` object. ```sh theme={null} curl "https://api.cometapi.com/v1beta/models/gemini-3-flash-preview:streamGenerateContent?alt=sse" \ -H "Content-Type: application/json" \ -H "x-goog-api-key: $COMETAPI_KEY" \ --no-buffer \ -d '{ "contents": [{"parts": [{"text": "Write a short poem about the stars"}]}] }' ``` *** ## Set system instructions To guide the model’s behavior across the entire conversation, use `systemInstruction`: ```sh theme={null} curl "https://api.cometapi.com/v1beta/models/gemini-3-flash-preview:generateContent" \ -H "Content-Type: application/json" \ -H "x-goog-api-key: $COMETAPI_KEY" \ -d '{ "contents": [{"parts": [{"text": "What is 2+2?"}]}], "systemInstruction": { "parts": [{"text": "You are a math tutor. Always show your work."}] } }' ``` *** ## Request JSON output To force structured JSON output, set `responseMimeType`. Optionally provide a `responseSchema` for strict schema validation: ```sh theme={null} curl "https://api.cometapi.com/v1beta/models/gemini-3-flash-preview:generateContent" \ -H "Content-Type: application/json" \ -H "x-goog-api-key: $COMETAPI_KEY" \ -d '{ "contents": [{"parts": [{"text": "List 3 planets with their distances from the sun"}]}], "generationConfig": { "responseMimeType": "application/json" } }' ``` *** ## Ground with Google Search To enable real-time web search, add a `googleSearch` tool: ```sh theme={null} curl "https://api.cometapi.com/v1beta/models/gemini-3-flash-preview:generateContent" \ -H "Content-Type: application/json" \ -H "x-goog-api-key: $COMETAPI_KEY" \ -d '{ "contents": [{"parts": [{"text": "Who won the euro 2024?"}]}], "tools": [{"google_search": {}}] }' ``` The response includes `groundingMetadata` with source URLs and confidence scores. *** ## Response example A typical response from CometAPI's Gemini endpoint: ```json theme={null} { "candidates": [ { "content": { "role": "model", "parts": [{"text": "Hello"}] }, "finishReason": "STOP", "avgLogprobs": -0.0023 } ], "usageMetadata": { "promptTokenCount": 5, "candidatesTokenCount": 1, "totalTokenCount": 30, "trafficType": "ON_DEMAND", "thoughtsTokenCount": 24, "promptTokensDetails": [{"modality": "TEXT", "tokenCount": 5}], "candidatesTokensDetails": [{"modality": "TEXT", "tokenCount": 1}] }, "modelVersion": "gemini-3-flash-preview", "createTime": "2026-03-25T04:21:43.756483Z", "responseId": "CeynaY3LDtvG4_UP0qaCuQY" } ``` The `thoughtsTokenCount` field in `usageMetadata` shows how many tokens the model spent on internal reasoning, even when thinking output is not included in the response. *** ## Compare with OpenAI-compatible endpoint | Feature | Gemini Native (`/v1beta/models/...`) | OpenAI-Compatible (`/v1/chat/completions`) | | ------------------------- | -------------------------------------------------------- | ------------------------------------------ | | Thinking control | `thinkingConfig` with `thinkingLevel` / `thinkingBudget` | Not available | | Google Search grounding | `tools: [\{"google_search": \{\}\}]` | Not available | | Google Maps grounding | `tools: [\{"googleMaps": \{\}\}]` | Not available | | Image generation modality | `responseModalities: ["IMAGE"]` | Not available | | Auth header | `x-goog-api-key` or `Bearer` | `Bearer` only | | Response format | Gemini native (`candidates`, `parts`) | OpenAI format (`choices`, `message`) | # Text and chat APIs Source: https://apidoc.cometapi.com/api/text/index Choose the CometAPI text and chat API that fits your request format: Chat Completions, Responses, Anthropic Messages, or Gemini content generation. Use CometAPI text model docs by matching your request format to the page that implements it. For OpenAI-compatible chat, start with Chat Completions or Responses; for provider-native formats, use the matching provider page. ## Choose a text and chat API Send OpenAI-compatible chat messages with a messages array. Use reasoning, multimodal output, and built-in tools through the Responses API. Call Claude-compatible Messages workflows with provider-native fields. Send Gemini native content generation requests. ## Call a text model Use any text-capable model ID from the [Models page](/overview/models) or the [model directory](https://www.cometapi.com/models/). The examples below call the OpenAI-compatible Chat Completions endpoint. These examples use the placeholder `your-model-id`. Replace it with an available text model ID from the [Models page](/overview/models) or [model directory](https://www.cometapi.com/models/) before you run the request. ```python Python theme={null} import os import requests response = requests.post( "https://api.cometapi.com/v1/chat/completions", headers={ "Authorization": "Bearer " + os.environ["COMETAPI_KEY"], "Content-Type": "application/json", }, json={ "model": "your-model-id", "messages": [ { "role": "user", "content": "Write one sentence about CometAPI.", } ], }, timeout=30, ) response.raise_for_status() result = response.json() print(result["choices"][0]["message"]["content"]) ``` ```javascript Node.js theme={null} const response = await fetch("https://api.cometapi.com/v1/chat/completions", { method: "POST", headers: { Authorization: `Bearer ${process.env.COMETAPI_KEY}`, "Content-Type": "application/json", }, body: JSON.stringify({ model: "your-model-id", messages: [ { role: "user", content: "Write one sentence about CometAPI.", }, ], }), }); if (!response.ok) { throw new Error(await response.text()); } const result = await response.json(); console.log(result.choices[0].message.content); ``` ```bash cURL theme={null} curl https://api.cometapi.com/v1/chat/completions \ -H "Authorization: Bearer $COMETAPI_KEY" \ -H "Content-Type: application/json" \ -d '{ "model": "your-model-id", "messages": [ { "role": "user", "content": "Write one sentence about CometAPI." } ] }' ``` ## Response example A successful response can look like this. Field values vary by model and request: ```json theme={null} { "id": "chatcmpl_example", "object": "chat.completion", "created": 1779960520, "model": "your-model-id", "choices": [ { "index": 0, "message": { "role": "assistant", "content": "CometAPI lets developers route model requests through one API surface." }, "finish_reason": "stop" } ], "usage": { "prompt_tokens": 12, "completion_tokens": 14, "total_tokens": 26 } } ``` ## Example model records This example model catalog response shows the `/api/models` envelope and one text model record shape. It is not a complete model list. ```bash cURL theme={null} curl https://api.cometapi.com/api/models ``` ```json theme={null} { "success": true, "page": 1, "page_size": 20, "total": 302, "data": [ { "created": 1773798949, "id": "your-text-model-id", "code": "your-text-model-id", "provider": "ExampleProvider", "provider_code": "example", "name": "Example text model", "model_type": "text", "features": [ "text-to-text" ], "endpoints": "{\n \"openai-chat\": {\n \"path\": \"/v1/chat/completions\",\n \"method\": \"POST\"\n }\n}", "pricing": { "currency": "USD / M Tokens", "input": 0.5, "output": 1.5, "per_request": null, "per_second": null } } ] } ``` ## Common errors Send `Authorization: Bearer $COMETAPI_KEY`. Use `https://api.cometapi.com/v1` for OpenAI-compatible requests. Choose a text-capable model from the [Models page](/overview/models). Remove optional fields, then add the fields back one at a time. ## Error codes and retry strategy Do not retry until the request body is fixed. Do not retry until the API key is present and valid. Check the base URL, path, and model ID before retrying. Retry with exponential backoff and reduce concurrency. Retry with backoff for transient provider or service errors. For implementation patterns, see [Error codes and retry strategy](/guides/error-codes-and-retry-strategy) and [Rate limits and concurrency](/guides/rate-limits-and-concurrency). ## Pricing and model directory Read how CometAPI exposes model IDs in the docs. Browse model availability and capabilities. Check pricing before you call a model. # Create a model response Source: https://apidoc.cometapi.com/api/text/responses api/openapi/text/post-responses.openapi.json POST /v1/responses Use CometAPI POST /v1/responses to create multimodal and stateful model responses with built-in tools and function calling. The Responses API extends [Chat Completions](/api/text/chat) with stateful conversations, built-in tools, multimodal file inputs, and reasoning control. It is the recommended endpoint for OpenAI o-series reasoning models, GPT-5 series, and Codex models. Different model providers support different request parameters and return varying response fields. Not all parameters listed in the playground above work with every model on CometAPI. *** ## Use stateful conversations Chain responses together using `previous_response_id` instead of managing message history yourself: ```python theme={null} import os from openai import OpenAI client = OpenAI( base_url="https://api.cometapi.com/v1", api_key=os.environ["COMETAPI_KEY"], ) # First turn response = client.responses.create( model="gpt-5.6-sol", input="What is quantum computing?", ) # Second turn — previous context is included automatically follow_up = client.responses.create( model="gpt-5.6-sol", input="Can you explain that more simply?", previous_response_id=response.id, ) print(follow_up.output_text) ``` *** ## Use built-in tools The Responses API includes platform-provided tools that require no configuration: | Tool | Purpose | | -------------------- | ---------------------------------------- | | `web_search_preview` | Search the web for real-time information | | `file_search` | Search through uploaded files | | `code_interpreter` | Execute Python code in a sandbox | To enable a built-in tool, add it to the `tools` array: ```python theme={null} response = client.responses.create( model="gpt-5.6-sol", input="Find the current price of Bitcoin", tools=[{"type": "web_search_preview"}], ) print(response.output_text) ``` *** ## Call custom functions Define functions the model can invoke with structured arguments: ```python theme={null} response = client.responses.create( model="gpt-5.6-sol", input="What's the weather in Tokyo?", tools=[{ "type": "function", "name": "get_weather", "description": "Get current weather for a location", "parameters": { "type": "object", "properties": { "location": {"type": "string"} }, "required": ["location"] } }], ) ``` When the model calls a function, the response `output` array contains a `function_call` item with the function name and parsed arguments. Execute the function and send the result back in a follow-up request. *** ## Request structured output To force JSON output matching a specific schema, use the `text.format` parameter: ```python theme={null} response = client.responses.create( model="gpt-5.6-sol", input="List 3 programming languages with their main use cases", text={ "format": { "type": "json_schema", "name": "languages", "strict": True, "schema": { "type": "object", "properties": { "languages": { "type": "array", "items": { "type": "object", "properties": { "name": {"type": "string"}, "use_case": {"type": "string"} }, "required": ["name", "use_case"], "additionalProperties": False } } }, "required": ["languages"], "additionalProperties": False } } }, ) ``` *** ## Configure reasoning For o-series and GPT-5 models, control reasoning depth with `reasoning.effort`: ```python theme={null} response = client.responses.create( model="o3", input="Solve this step by step: if f(x) = x^3 - 6x^2 + 11x - 6, find all roots.", reasoning={"effort": "high"}, # "low", "medium", or "high" ) print(response.output_text) ``` Higher reasoning effort produces more thorough answers but uses more tokens. Use `"low"` for simple queries and `"high"` for complex multi-step problems. *** ## Stream responses To receive incremental output, set `stream` to `true`. The API sends server-sent events (SSE) in this order: 1. `response.created` — Response object initialized 2. `response.in_progress` — Generation started 3. `response.output_item.added` — New output item (message or tool call) 4. `response.content_part.added` — Content part started 5. `response.output_text.delta` — Text chunk (contains `delta` field) 6. `response.output_text.done` — Text generation complete for this content part 7. `response.content_part.done` — Content part finished 8. `response.output_item.done` — Output item finished 9. `response.completed` — Full response with `usage` data Stream a response with the Python SDK: ```python theme={null} stream = client.responses.create( model="gpt-5.6-sol", input="Write a haiku about coding", stream=True, ) for event in stream: if event.type == "response.output_text.delta": print(event.delta, end="") ``` *** For in-depth guides on each capability, see the OpenAI documentation: [Text](https://developers.openai.com/docs/guides/text) · [Images](https://developers.openai.com/docs/guides/images) · [PDF files](https://developers.openai.com/docs/guides/pdf-files) · [Structured Outputs](https://developers.openai.com/docs/guides/structured-outputs) · [Function Calling](https://developers.openai.com/docs/guides/function-calling) · [Conversation State](https://developers.openai.com/docs/guides/conversation-state) · [Built-in Tools](https://developers.openai.com/docs/guides/tools) · [Reasoning](https://developers.openai.com/docs/guides/reasoning) # Create a Flux 3 video Source: https://apidoc.cometapi.com/api/video/flux-3/create api/openapi/video/flux-3/post-create.openapi.json POST /v1/videos Create a Flux 3 text-to-video or image-to-video task through CometAPI with a 720p or 1080p size preset. Use this endpoint to create a Flux 3 video task. The API returns a task ID, so store the returned `id` for status and content requests. `POST /v1/videos` uses `multipart/form-data`. Send scalar controls as form fields. Send one reference image as an HTTPS URL or an uploaded file. Choose only one image input method. Do not send `images` and `input_reference` in the same request. ## Choose an input mode | Goal | Required fields | Optional fields | | ----------------------- | ---------------------------------------------------- | ----------------- | | Text-to-video | `model=flux-3`, `prompt` | `seconds`, `size` | | HTTPS image-to-video | `model=flux-3`, `prompt`, one `images` field | `seconds`, `size` | | Uploaded image-to-video | `model=flux-3`, `prompt`, one `input_reference` file | `seconds`, `size` | ## Use a reference image For an HTTPS reference image, send one publicly accessible image URL in the `images` multipart field. For an uploaded reference image, send one PNG or JPEG file in the `input_reference` multipart field. The file can be up to 20 MB. Describe the motion, camera behavior, and visual details that the generated video should preserve from the reference image. ## Set duration and size Set `seconds` to an integer from `5` through `20`. The default is `10` seconds. Set `size` to one of these exact `WxH` preset values: | Resolution tier | Size | | --------------- | ----------- | | `720p` | `1280x720` | | `1080p` | `1920x1080` | The size value selects the output resolution tier. Encoded text-to-video dimensions can be codec-aligned rather than literal. For image-to-video, the reference image can also determine the final framing and aspect ratio. ## Task flow Send the multipart form request and store the returned `id`. Call [Retrieve a Flux 3 video](./retrieve) until `status` is `completed` or `failed`. When the task is `completed`, call [Download Flux 3 video content](./retrieve-content) to save the MP4 file. # Retrieve a Flux 3 video Source: https://apidoc.cometapi.com/api/video/flux-3/retrieve api/openapi/video/flux-3/get-retrieve.openapi.json GET /v1/videos/{task_id} Retrieve a Flux 3 video task by task ID, including its status, progress, timestamps, result URL, or failure details. Use this endpoint after you create a Flux 3 video task. The response includes `video_url` when the task is completed. ## Check these fields * `status` is `queued`, `in_progress`, `completed`, or `failed`. * `progress` is a coarse completion percentage from `0` through `100`. * `video_url` appears when the task is completed. * `error` appears when the task fails. ## Poll the task Start with [Create a Flux 3 video](./create) and store the returned `id`. Send the task ID to this endpoint until `status` is `completed` or `failed`. When `status` is `completed`, call [Download Flux 3 video content](./retrieve-content). # Download Flux 3 video content Source: https://apidoc.cometapi.com/api/video/flux-3/retrieve-content api/openapi/video/flux-3/get-retrieve-content.openapi.json GET /v1/videos/{task_id}/content Download the completed MP4 file for a Flux 3 video task through the unified content route. Use this endpoint to download the MP4 file for a completed Flux 3 video task. ## Before you download * Create a task with [Create a Flux 3 video](./create). * Poll with [Retrieve a Flux 3 video](./retrieve) until `status` is `completed`. * Pass the same task ID to this endpoint. ## Store completed media The response body is binary `video/mp4` content. Save the bytes to your own storage when your application needs durable access to the generated media. # Create a HappyHorse video Source: https://apidoc.cometapi.com/api/video/happyhorse/create api/openapi/video/happyhorse/post-create.openapi.json POST /v1/videos Create a HappyHorse text-to-video or reference-image video task through CometAPI with POST /v1/videos, then poll the task and download the completed MP4 file. Use this endpoint to create a HappyHorse video task. The API returns a task ID immediately, so store the returned `id` and poll the task until it reaches a terminal status. `POST /v1/videos` uses `multipart/form-data`; pass scalar controls as form fields and reference images as `input_reference` file fields. ## Choose an input mode | Goal | Model | Required fields | Optional fields | | ------------------ | ---------------------------------- | --------------------------------------------- | ---------------------------------------- | | Text-to-video | `happyhorse-1.0`, `happyhorse-1.1` | `model`, `prompt` | `seconds`, `size` | | Reference-to-video | `happyhorse-1.0`, `happyhorse-1.1` | `model`, `prompt`, one `input_reference` file | `seconds`, `size`, more reference images | For reference-to-video, upload 1-9 reference images by repeating the `input_reference` multipart field. CometAPI sends each uploaded file as a HappyHorse reference image. Use JPEG, JPG, PNG, or WEBP images up to 20 MB each; for best results, use images with a shortest side of at least 400 px. ## Set duration and size | Model ID | `seconds` | Default | | ---------------- | ---------------- | ------------------------ | | `happyhorse-1.0` | integer `3`-`15` | `5` seconds, `1920x1080` | | `happyhorse-1.1` | integer `3`-`15` | `5` seconds, `1920x1080` | Set `size` to an exact `WxH` value. | Model | Frame shape | `size` values | | ---------------- | --------------------- | ----------------------- | | `happyhorse-1.0` | Landscape | `1280x720`, `1920x1080` | | | Portrait | `720x1280`, `1080x1920` | | | Square | `1440x1440` | | `happyhorse-1.1` | Landscape | `1280x720`, `1920x1080` | | | Portrait | `720x1280`, `1080x1920` | | | Square | `1440x1440` | | | Classic landscape | `1440x1080` | | | Classic portrait | `720x960`, `1080x1440` | | | Wide landscape | `2520x1080` | | | Wide portrait | `1080x2520` | | | Near-square landscape | `900x720`, `1350x1080` | | | Near-square portrait | `720x900`, `1080x1350` | ## Task flow Send the multipart form request and store the returned `id`. Call [Retrieve a HappyHorse video](./retrieve) until `status` is `completed`, `failed`, or `error`. When the task is `completed`, call [Retrieve HappyHorse video content](./retrieve-content) to download the MP4 file. # Retrieve a HappyHorse video Source: https://apidoc.cometapi.com/api/video/happyhorse/retrieve api/openapi/video/happyhorse/get-retrieve.openapi.json GET /v1/videos/{task_id} Retrieve a HappyHorse video task by task ID, including status, progress, timestamps, and the completed video URL. Use this endpoint after you create a HappyHorse video task. It returns the task state and includes `video_url` after the task is completed. ## Check these fields * `status` tells you whether the task is `queued`, `in_progress`, `completed`, `failed`, or `error`. * `progress` is a coarse completion percentage. * `video_url` appears on completed responses. * `error` appears when a task fails. ## Polling flow Start with [Create a HappyHorse video](./create) and store the returned `id`. Send the task ID to this endpoint until `status` reaches `completed`, `failed`, or `error`. When `status` is `completed`, call [Retrieve HappyHorse video content](./retrieve-content). # Download HappyHorse video content Source: https://apidoc.cometapi.com/api/video/happyhorse/retrieve-content api/openapi/video/happyhorse/get-retrieve-content.openapi.json GET /v1/videos/{task_id}/content Download the completed MP4 file for a HappyHorse video task through the content route. Use this endpoint to download the MP4 file for a completed HappyHorse video task. If the task is still running, the API returns a JSON error instead of video bytes. ## Before you download * Create a task with [Create a HappyHorse video](./create). * Poll with [Retrieve a HappyHorse video](./retrieve) until `status` is `completed`. * Pass the same task ID to this endpoint. ## Store completed media The response body is binary `video/mp4` content. Save the bytes to your own storage when your application needs durable access to the generated media. # Video generation APIs Source: https://apidoc.cometapi.com/api/video/index Choose CometAPI video routes for Seedance, HappyHorse, MiniMax H3, Flux 3, Sora 2, Veo 3, Wan, xAI, Vidu, Omni, Kling, and Runway workflows. Use CometAPI video model docs by choosing the provider workflow that matches your job type. Most video endpoints create asynchronous tasks, so save the task ID and use polling to retrieve results. Add callbacks only when the model-specific page documents callback support. ## Choose a video API Create Seedance video tasks. Create HappyHorse text-to-video jobs. Create MiniMax H3 text-to-video or reference-image video tasks. Create Flux 3 text-to-video or image-to-video tasks. Create Sora 2 video jobs. Query Sora video jobs. Create Veo video jobs. Create Wan text-to-video or image-to-video jobs. Generate xAI video jobs. Create Vidu text-to-video or image-to-video jobs. Create beta Omni video jobs. Generate Kling videos from text prompts. Generate Runway videos from images. ## Create and poll a video task Use a video-capable model ID from the [Models page](/overview/models) or the [model directory](https://www.cometapi.com/models/). The examples below create a video task with `POST /v1/videos`, then poll the returned task ID until the task reaches a terminal state. These examples use the placeholder `your-video-model-id`. Replace it with an available video model ID from the [Models page](/overview/models) or [model directory](https://www.cometapi.com/models/) before you run the request. Open [Create a Seedance video](/api/video/seedance/create) and [Retrieve a Seedance video](/api/video/seedance/query) to use the API playgrounds and endpoint schemas. ```python Python theme={null} import os import time import requests headers = {"Authorization": "Bearer " + os.environ["COMETAPI_KEY"]} create_response = requests.post( "https://api.cometapi.com/v1/videos", headers=headers, data={ "model": "your-video-model-id", "prompt": "A calm camera move across a desk with a paper airplane", }, timeout=30, ) create_response.raise_for_status() task = create_response.json() task_id = task["id"] terminal_statuses = {"completed", "failed", "error"} while True: poll_response = requests.get( f"https://api.cometapi.com/v1/videos/{task_id}", headers=headers, timeout=30, ) poll_response.raise_for_status() result = poll_response.json() print(result["status"], result.get("progress")) if result["status"] in terminal_statuses: print(result.get("video_url")) break time.sleep(10) ``` ```javascript Node.js theme={null} const form = new FormData(); form.append("model", "your-video-model-id"); form.append("prompt", "A calm camera move across a desk with a paper airplane"); const createResponse = await fetch("https://api.cometapi.com/v1/videos", { method: "POST", headers: { Authorization: `Bearer ${process.env.COMETAPI_KEY}`, }, body: form, }); if (!createResponse.ok) { throw new Error(await createResponse.text()); } const task = await createResponse.json(); const terminalStatuses = new Set(["completed", "failed", "error"]); while (true) { const pollResponse = await fetch( `https://api.cometapi.com/v1/videos/${task.id}`, { headers: { Authorization: `Bearer ${process.env.COMETAPI_KEY}`, }, }, ); if (!pollResponse.ok) { throw new Error(await pollResponse.text()); } const result = await pollResponse.json(); console.log(result.status, result.progress); if (terminalStatuses.has(result.status)) { console.log(result.video_url); break; } await new Promise((resolve) => setTimeout(resolve, 10_000)); } ``` Create the task with one direct request: ```bash theme={null} curl https://api.cometapi.com/v1/videos \ -H "Authorization: Bearer $COMETAPI_KEY" \ -F "model=your-video-model-id" \ -F "prompt=A calm camera move across a desk with a paper airplane" ``` Query the task once with the returned ID: ```bash theme={null} curl "https://api.cometapi.com/v1/videos/" \ -H "Authorization: Bearer $COMETAPI_KEY" ``` ## Response examples A successful create response can look like this. Store the task ID before polling: ```json theme={null} { "id": "task_example", "task_id": "task_example", "object": "video", "model": "your-video-model-id", "status": "queued", "progress": 0, "created_at": 1779872000 } ``` A successful polling response can look like this. Completed responses can include `video_url`; some provider formats use model-specific result fields or the video content route when that route is documented: ```json theme={null} { "id": "task_example", "object": "video", "model": "your-video-model-id", "status": "completed", "progress": 100, "completed_at": 1779872300, "video_url": "https://example.com/generated-video.mp4" } ``` ## Example model records This example model catalog response shows the `/api/models` envelope and one video model record shape. It is not a complete model list. ```bash cURL theme={null} curl https://api.cometapi.com/api/models ``` ```json theme={null} { "success": true, "page": 1, "page_size": 20, "total": 302, "data": [ { "created": 1767529753, "id": "your-video-model-id", "code": "your-video-model-id", "provider": "ExampleProvider", "provider_code": "example", "name": "Example video model", "model_type": "video", "features": [ "text-to-video" ], "endpoints": "{\n \"seedance\": {\n \"path\": \"/v1/videos\",\n \"method\": \"POST\"\n }\n}", "pricing": { "currency": "USD / M Tokens", "input": null, "output": null, "per_request": null, "per_second": 0.024 } } ] } ``` ## Common errors Store the ID from the create response before returning from your job handler. Add delay and backoff between status checks. Use the duration and resolution fields documented for the selected video endpoint. Treat `video_url` as optional and fall back to model-specific result fields or the content route when available. Use polling as the source of truth and verify that your callback URL accepts POST requests. ## Error codes and retry strategy Do not retry until the prompt, files, duration, or size fields are fixed. Do not retry until the API key is present and valid. Check the task ID, base URL, path, and model ID before retrying. Reduce upload size before retrying. Retry with exponential backoff and reduce create or polling concurrency. Retry task creation with backoff; keep polling existing tasks unless the task reaches a terminal error. For implementation patterns, see [Error codes and retry strategy](/guides/error-codes-and-retry-strategy), [Rate limits and concurrency](/guides/rate-limits-and-concurrency), and [Webhook and polling for video generation](/guides/webhook-and-polling-for-video-generation). ## Pricing and model directory Read how CometAPI exposes model IDs in the docs. Browse model availability and capabilities. Check pricing before you call a model. # Create a MiniMax H3 video Source: https://apidoc.cometapi.com/api/video/minimax-h3/create api/openapi/video/minimax-h3/post-create.openapi.json POST /v1/videos Create a MiniMax H3 text-to-video or reference-image video task through CometAPI with an exact WxH size. Use this endpoint to create a MiniMax H3 video task. The API returns a task ID, so store the returned `id` for status and content requests. `POST /v1/videos` uses `multipart/form-data`. Send scalar controls as form fields. Repeat the relevant image field when you use multiple reference images. ## Choose an input mode | Goal | Required fields | Optional fields | | ------------------------- | ----------------------------------------------------------------- | ----------------- | | Text-to-video | `model=minimax-h3`, `prompt` | `seconds`, `size` | | URL reference images | `model=minimax-h3`, `prompt`, one or more `images` fields | `seconds`, `size` | | Uploaded reference images | `model=minimax-h3`, `prompt`, one or more `input_reference` files | `seconds`, `size` | ## Use reference images For HTTPS reference images, repeat the `images` multipart field. Each value must be a publicly accessible HTTPS image URL. For uploaded reference images, repeat the `input_reference` multipart field. Upload PNG or JPEG files up to 20 MB each. A request can contain up to nine reference images across the URL and file fields. Describe the visual details that the generated video should preserve. ## Set duration and size Set `seconds` to an integer from `5` through `15`. The default is `5` seconds. Set `size` to an exact `WxH` value. For predictable output dimensions, choose a canonical size from the table below. Other `WxH` values can be normalized to the nearest supported aspect ratio and size. | Resolution | Aspect Ratio | Size | | ---------- | ------------ | ----------- | | `768P` | `21:9` | `1536x672` | | `768P` | `16:9` | `1344x768` | | `768P` | `4:3` | `1024x768` | | `768P` | `1:1` | `768x768` | | `768P` | `3:4` | `768x1024` | | `768P` | `9:16` | `768x1344` | | `2K` | `21:9` | `2912x1280` | | `2K` | `16:9` | `2560x1440` | | `2K` | `4:3` | `1920x1440` | | `2K` | `1:1` | `1440x1440` | | `2K` | `3:4` | `1440x1920` | | `2K` | `9:16` | `1440x2560` | ## Task flow Send the multipart form request and store the returned `id`. Call [Retrieve a MiniMax H3 video](./retrieve) until `status` is `completed` or `failed`. When the task is `completed`, call [Download MiniMax H3 video content](./retrieve-content) to save the MP4 file. # Retrieve a MiniMax H3 video Source: https://apidoc.cometapi.com/api/video/minimax-h3/retrieve api/openapi/video/minimax-h3/get-retrieve.openapi.json GET /v1/videos/{task_id} Retrieve a MiniMax H3 video task by task ID, including its status, progress, timestamps, result URL, or failure details. Use this endpoint after you create a MiniMax H3 video task. The response includes `video_url` when the task is completed. ## Check these fields * `status` is `queued`, `in_progress`, `completed`, or `failed`. * `progress` is a coarse completion percentage from `0` through `100`. * `video_url` appears when the task is completed. * `error` appears when the task fails. ## Poll the task Start with [Create a MiniMax H3 video](./create) and store the returned `id`. Send the task ID to this endpoint until `status` is `completed` or `failed`. When `status` is `completed`, call [Download MiniMax H3 video content](./retrieve-content). # Download MiniMax H3 video content Source: https://apidoc.cometapi.com/api/video/minimax-h3/retrieve-content api/openapi/video/minimax-h3/get-retrieve-content.openapi.json GET /v1/videos/{task_id}/content Download the completed MP4 file for a MiniMax H3 video task through the unified content route. Use this endpoint to download the MP4 file for a completed MiniMax H3 video task. ## Before you download * Create a task with [Create a MiniMax H3 video](./create). * Poll with [Retrieve a MiniMax H3 video](./retrieve) until `status` is `completed`. * Pass the same task ID to this endpoint. ## Store completed media The response body is binary `video/mp4` content. Save the bytes to your own storage when your application needs durable access to the generated media. # Create a Seedance video Source: https://apidoc.cometapi.com/api/video/seedance/create api/openapi/video/seedance/post-seedance-create.openapi.json POST /v1/videos Create a Seedance video task on CometAPI. Use text prompts or reference images, select a duration, and request an exact WxH output size. Choose a documented `WxH` value from the table below for the `size` field. Use `doubao-seedance-2-0-mini` exactly for Seedance 2.0 Mini. The shortened `seedance-mini` value is not a valid model ID. ## Supported model IDs Use one of these exact values for the `model` field. | Model | Exact model ID | Modes and resolution tiers | Supported `seconds` | | ----------------- | -------------------------- | ------------------------------------------------------------ | ------------------- | | Seedance 2.5 | `seedance-2-5-260628` | Text-to-video, image-to-video; `480p`, `720p` | `4`-`30` | | Seedance 2.0 | `doubao-seedance-2-0` | Text-to-video, image-to-video; `480p`, `720p`, `1080p`, `4K` | `4`-`15` | | Seedance 2.0 Fast | `doubao-seedance-2-0-fast` | Text-to-video, image-to-video; `480p`, `720p` | `4`-`15` | | Seedance 2.0 Mini | `doubao-seedance-2-0-mini` | Text-to-video, image-to-video; `480p`, `720p` | `4`-`15` | | Seedance 1.5 Pro | `doubao-seedance-1-5-pro` | Text-to-video; `480p`, `720p`, `1080p` | `4`-`12` | | Seedance 1.0 Pro | `doubao-seedance-1-0-pro` | Text-to-video; `480p`, `720p`, `1080p` | `2`-`10` | ## Use reference images For Seedance 2.5 image-to-video requests, upload the reference image through the multipart `input_reference` field. The example on this page uses one file. Seedance 2.0, Seedance 2.0 Fast, and Seedance 2.0 Mini also accept `input_reference`. For advanced multi-reference prompts with those 2.0 models, repeat the same multipart field in upload order. One Mini production request with a single `input_reference` completed at the `720x1280` output size. That check confirmed request completion, but it did not isolate the reference image's visual effect from the prompt. Seedance 2.0 is sensitive to how the prompt connects each reference image to the scene. Refer to the uploaded files by order, such as `[Image 1]`, `[Image 2]`, and `[Image 3]`, then assign each image a clear role: * Use `[Image 1]` for the main subject, character, or product. * Use `[Image 2]` for a secondary subject, prop, or companion. * Use `[Image 3]` for the background, setting, lighting, or style. Describe what should stay recognizable, what can change, the action, camera motion, visual style, and scene. A vague prompt can make the generated video look like the reference image was not used, even when the upload was accepted. This prompt structure is more reliable than only listing images: ```text theme={null} Use the uploaded images in order: keep the boy wearing glasses and a blue T-shirt from [Image 1], add the corgi puppy from [Image 2], and use the lawn from [Image 3] as the setting. Create a 4-second 3D cartoon video with the boy and puppy sitting together, a slow camera push-in, soft daylight, and no extra characters. ``` ## Duration by model If you omit `seconds`, CometAPI requests a 5-second clip. Send `seconds` as a string when you need a specific duration. | Model family | Supported `seconds` | Default | Boundary behavior | | ------------------------------------------------------ | ------------------- | ------- | ----------------------------- | | Seedance 2.5 | `4`-`30` | `5` | Use integer seconds in range. | | Seedance 2.0, Seedance 2.0 Fast, and Seedance 2.0 Mini | `4`-`15` | `5` | Use integer seconds in range. | | Seedance 1.5 Pro | `4`-`12` | `5` | Use integer seconds in range. | | Seedance 1.0 Pro | `2`-`10` | `5` | Use integer seconds in range. | ## Size support by model ### Seedance 2.5 The following exact sizes apply to both text-to-video and image-to-video requests with `seedance-2-5-260628`. | Resolution class | `16:9` | `4:3` | `1:1` | `3:4` | `9:16` | `21:9` | | ---------------- | ---------- | ---------- | --------- | ---------- | ---------- | ---------- | | `480p` | `854x480` | `752x560` | `640x640` | `560x752` | `480x854` | `992x432` | | `720p` | `1280x720` | `1112x834` | `960x960` | `834x1112` | `720x1280` | `1470x630` | ### Earlier Seedance models The table below keeps the exact `WxH` values in one place. Seedance 2.0 Fast uses only the `480p` and `720p` values in the fifth column. The `1080p` values in that column apply to Seedance 1.5 Pro and standard Seedance 2.0. The `4K` values apply only to standard Seedance 2.0. In the Mini column, `—` means the resolution is not supported. | Resolution class | Aspect ratio | Seedance 2.0 Mini | Seedance 1.0 series | Seedance 1.5 Pro / standard Seedance 2.0 / Fast | | ---------------- | ------------ | ----------------- | ------------------- | ----------------------------------------------- | | `480p` | `16:9` | `864x496` | `864x480` | `864x496` | | | `4:3` | `752x560` | `736x544` | `752x560` | | | `1:1` | `640x640` | `640x640` | `640x640` | | | `3:4` | `560x752` | `544x736` | `560x752` | | | `9:16` | `496x864` | `480x864` | `496x864` | | | `21:9` | `992x432` | `960x416` | `992x432` | | `720p` | `16:9` | `1280x720` | `1248x704` | `1280x720` | | | `4:3` | `1112x834` | `1120x832` | `1112x834` | | | `1:1` | `960x960` | `960x960` | `960x960` | | | `3:4` | `834x1112` | `832x1120` | `834x1112` | | | `9:16` | `720x1280` | `704x1248` | `720x1280` | | | `21:9` | `1470x630` | `1504x640` | `1470x630` | | `1080p` | `16:9` | — | `1920x1088` | `1920x1080` | | | `4:3` | — | `1664x1248` | `1664x1248` | | | `1:1` | — | `1440x1440` | `1440x1440` | | | `3:4` | — | `1248x1664` | `1248x1664` | | | `9:16` | — | `1088x1920` | `1080x1920` | | | `21:9` | — | `2176x928` | `2206x946` | | `4K` | `16:9` | — | — | `3840x2160` (Seedance 2.0 only) | | | `4:3` | — | — | `3326x2494` (Seedance 2.0 only) | | | `1:1` | — | — | `2880x2880` (Seedance 2.0 only) | | | `3:4` | — | — | `2494x3326` (Seedance 2.0 only) | | | `9:16` | — | — | `2160x3840` (Seedance 2.0 only) | | | `21:9` | — | — | `4398x1886` (Seedance 2.0 only) | Seedance 2.0 Mini supports `480p` and `720p`, not `1080p` or `4K`. In one production check, a Mini request for `1920x1080` produced `1280x720`. Choose the documented `WxH` value for the target model. Exact `WxH` support remains model-dependent, so inspect the completed media before relying on an undocumented size. # Retrieve a Seedance video Source: https://apidoc.cometapi.com/api/video/seedance/query api/openapi/video/seedance/get-seedance-query.openapi.json GET /v1/videos/{id} Poll a Seedance video task by id on CometAPI with GET /v1/videos/{id}. Works for Seedance 1.0 Pro, 1.5 Pro, and 2.0 tasks. Returns the current status, progress, and the signed video_url after the task reaches completed. Use this endpoint to read the state of a task created through [Create a Seedance video](./create). The `id` in the path is the value returned by the create call, regardless of which Seedance model produced the task. The response body is the video task object itself. Read `status`, `progress`, and `video_url` at the top level. ## Status machine The API returns lowercase status strings. `queued` and `in_progress` are non-terminal; `completed`, `failed`, and `error` are terminal and the task will not move again. | Status | Meaning | Terminal | | ------------- | ------------------------------------------------- | -------- | | `queued` | Accepted and queued for rendering. | no | | `in_progress` | Rendering in progress. | no | | `completed` | Finished. `video_url` is present in the response. | yes | | `failed` | The provider rejected the task. | yes | | `error` | An internal error prevented completion. | yes | ## Poll cadence Poll every 10 to 20 seconds. Most jobs finish within 1 to 3 minutes depending on model, duration, and size. ```python theme={null} import os import time import requests TASK_ID = "" headers = {"Authorization": "Bearer " + os.environ["COMETAPI_KEY"]} TERMINAL = {"completed", "failed", "error"} while True: response = requests.get( f"https://api.cometapi.com/v1/videos/{TASK_ID}", headers=headers, timeout=15, ) response.raise_for_status() data = response.json() if data["status"] in TERMINAL: print(data.get("video_url")) break time.sleep(10) ``` ## Fields to watch * `status` — drives the stop condition for your polling loop. * `progress` — integer 0 to 100 that you can surface in a UI. * `video_url` — signed download URL, present on `completed` responses. Seedance downloads use this URL directly instead of a separate `/v1/videos/{id}/content` route. The signature is time-limited; download or re-host the file before the signature expires. * `completed_at` — optional Unix timestamp returned by the platform. Do not use it to stop polling; use `status` instead. * `model` — echoes the Seedance model id used when the task was created. ## Common errors * HTTP `400` with `message: "task_not_exist"` means the `id` is unknown. Confirm that you captured the `id` from a successful POST `/v1/videos` response and that you use it verbatim. * HTTP `401` means the bearer token is missing or invalid. Check that the request header is `Authorization: Bearer $COMETAPI_KEY`. # Create a Sora 2 video Source: https://apidoc.cometapi.com/api/video/sora-2/create api/openapi/video/sora-2/post-create.openapi.json POST /v1/videos Use POST /v1/videos to create Sora 2 video generation tasks from text prompts or reference images, then poll status by task ID for results. Use this endpoint to start a Sora render job from text, or from text plus one reference image. The API returns a video id immediately and does not wait for the render to finish. ## Start with the smallest useful job * Use `sora-2` for faster iteration or `sora-2-pro` when output quality matters more than speed * Keep `seconds` at `4` for your first request * Start with `size: 1280x720` unless you specifically need portrait output * Upload at most one reference image ## Duration and size | Setting | Supported values | Default starting point | Boundary behavior | | ----------------------- | ------------------------------------------------------ | ------------------------------------ | ---------------------------------------------------------- | | `seconds` | `4`, `8`, `12`, `16`, `20` | `4` | Other values are not part of the Sora video request shape. | | `size` for `sora-2` | `1280x720`, `720x1280` | `1280x720` | Use landscape or portrait orientation. | | `size` for `sora-2-pro` | `1792x1024`, `1024x1792`, plus the standard Sora sizes | `1792x1024` for landscape Pro output | Use the larger Pro sizes only with a Pro model. | Sora requires the `size` field in exact `WxH` form. Resolution tokens such as `720p` and ratio labels such as `16:9` are not valid Sora `size` values on this endpoint. ## End-to-end flow Send `model`, `prompt`, `seconds`, and `size`, then save the returned `id`. Call [Retrieve Video](./retrieve) until the status becomes `completed` or `failed`. When the render is done, fetch the file with [Retrieve Video Content](./retrieve-content). ## Sora behavior that still applies OpenAI documents the same create -> retrieve -> download flow in the Videos API. On CometAPI you keep the Sora request shape, but use the CometAPI base URL and key. Finished download URLs are temporary, so copy completed assets into your own storage if you need long retention. # Retrieve a Sora 2 video Source: https://apidoc.cometapi.com/api/video/sora-2/retrieve api/openapi/video/sora-2/get-retrieve.openapi.json GET /v1/videos/{video_id} Use CometAPI GET /v1/videos/{video_id} to retrieve Sora 2 video status, progress, and metadata like duration, dimensions, timestamps, and expiry. Use this endpoint after you start a Sora job. It reports the current job state, the configured size and duration, and any error returned by the provider. ## Watch these fields * `status` for the lifecycle state * `progress` for a coarse progress signal * `error` when the provider rejects or fails the job * `expires_at` after completion if you need to know when temporary assets expire ## Poll until completion Start with [Create Video](./create). Pass the returned `id` here and keep checking until the job reaches `completed` or `failed`. When the job is `completed`, move to [Retrieve Video Content](./retrieve-content). ## Response shape on CometAPI This step matches the Sora polling workflow closely. CometAPI keeps the OpenAI-style object shape so you can wire status checks with minimal translation. # Download Sora 2 video content Source: https://apidoc.cometapi.com/api/video/sora-2/retrieve-content api/openapi/video/sora-2/get-retrieve-content.openapi.json GET /v1/videos/{video_id}/content Fetch generated Sora 2 video binary data via GET /v1/videos/{video_id}/content in CometAPI to download completed video outputs by video_id. Use this endpoint to download the finished Sora output after the job reaches `completed`. Until then, it returns an error instead of a video file. ## Before you download * Wait until [Retrieve Video](./retrieve) reports `status: completed` * Pass the `video_id` from the create step * Store the file in your own bucket or CDN if you need it to outlive the provider's temporary delivery window ## Download flow Start with [Create Video](./create). Use [Retrieve Video](./retrieve) until the job reaches `completed`. Call this endpoint to download the MP4 or another supported asset variant. ## Temporary delivery window Once the render is complete, retrieve the file promptly. The provider's delivery URL is not permanent. # Create a Veo 3 video Source: https://apidoc.cometapi.com/api/video/veo3/create api/openapi/video/veo3/post-create.openapi.json POST /v1/videos Generate Veo 3.1 videos asynchronously through CometAPI with POST /v1/videos, then poll the task and download the completed MP4 file. Use this endpoint to start a Veo 3.1 video task. The API returns a task ID immediately, so store the returned `id` and poll the task until it reaches a terminal status. `POST /v1/videos` uses `multipart/form-data`; pass scalar controls as form fields and media inputs as `input_reference` file fields. ## Choose a model | Model ID | When to use it | Notes | | ------------- | --------------------------------------------------------- | ----------------------- | | `veo3.1-fast` | Default choice for most short clips | Faster Veo 3.1 route. | | `veo3.1` | Use when you specifically want the standard Veo 3.1 model | Standard Veo 3.1 route. | ## Choose an input mode | Goal | Required fields | Optional fields | | -------------- | ------------------------------------ | ----------------- | | Text-to-video | `model`, `prompt` | `seconds`, `size` | | Image-to-video | `model`, `prompt`, `input_reference` | `seconds`, `size` | ## Set duration and size For the OpenAI-compatible route, use `seconds` for duration and `size` for the output size. Send values as form fields. | Model ID | `seconds` | Default | | ------------- | ------------- | ----------------------- | | `veo3.1-fast` | `4`, `6`, `8` | `4` seconds, `1280x720` | | `veo3.1` | `4`, `6`, `8` | `4` seconds, `1280x720` | Set `size` to one of the WxH values below. | Resolution tier | Aspect ratio | `size` (`WxH`) | | --------------- | ------------ | -------------- | | `720p` | `16:9` | `1280x720` | | | `9:16` | `720x1280` | | `1080p` | `16:9` | `1920x1080` | | `4K` | `16:9` | `3840x2160` | ## Task flow Send the multipart form request and store the returned `id`. Use [Veo3 Retrieve](./retrieve) until `status` is `completed`, `failed`, or `error`. When the task is `completed`, download the MP4 file from the completed task response. # Retrieve a Veo 3 video Source: https://apidoc.cometapi.com/api/video/veo3/retrieve api/openapi/video/veo3/get-retrieve.openapi.json GET /v1/videos/{video_id} Use CometAPI Veo3 Retrieve API (GET /v1/videos/{video_id}) to fetch status, query metadata, or download Veo3 video generation results by video_id. Use this endpoint to poll a Veo job. It returns the current task state and the resolved provider model information. ## Polling loop Start with [Veo3 Async Generation](./create) and save the returned `id`. Keep calling this endpoint until the job leaves `queued` or `in_progress` and reaches a finished state. Once the output is ready, move it into your own storage if your application needs a durable copy. ## Why the model ID may change The response may show the resolved provider model ID rather than the alias you submitted. This is expected behavior. # Create a Vidu video Source: https://apidoc.cometapi.com/api/video/vidu/create api/openapi/video/vidu/post-create.openapi.json POST /v1/videos Create a Vidu Q3 text-to-video or image-to-video task through CometAPI with POST /v1/videos, then poll the task and download the completed MP4 file. Use this endpoint to create a Vidu Q3 text-to-video or image-to-video task. The API returns a task ID immediately, so store the returned `id` and poll the task until it reaches a terminal status. `POST /v1/videos` uses `multipart/form-data`. Send scalar controls as form fields and reference images as `input_reference` file fields. ## Choose an input mode | Goal | Required fields | Optional fields | | -------------- | --------------------------------------------- | ----------------- | | Text-to-video | `model`, `prompt` | `seconds`, `size` | | Image-to-video | `model`, `prompt`, one `input_reference` file | `seconds`, `size` | To confirm a Vidu model ID that is available to your API key, use [List available models](/guides/how-to-list-available-models). ## Use reference images For image-to-video, upload one reference image through the `input_reference` multipart field. The file can be up to 20 MB. The image guides the composition and appearance of the generated video. Use the prompt to describe motion, camera behavior, and details that the video should preserve. ## Set duration and size | Model ID | `seconds` | Default | | -------------- | ---------------- | ----------------------- | | `viduq3-turbo` | integer `1`-`16` | `5` seconds, `1280x720` | | `viduq3` | integer `1`-`16` | `5` seconds, `1280x720` | Set `size` to one of the WxH values below. | Resolution tier | Aspect ratio | `size` (`WxH`) | | --------------- | ------------ | -------------- | | `540p` | `16:9` | `960x528` | | `720p` | `16:9` | `1280x720` | | `1080p` | `16:9` | `1920x1080` | ## Task flow Send the multipart form request and store the returned `id`. Call [Retrieve a Vidu video](./retrieve) until `status` is `completed`, `failed`, or `error`. When the task is `completed`, call [Retrieve Vidu video content](./retrieve-content) to download the MP4 file. # Retrieve a Vidu video Source: https://apidoc.cometapi.com/api/video/vidu/retrieve api/openapi/video/vidu/get-retrieve.openapi.json GET /v1/videos/{task_id} Retrieve a Vidu video task by task ID, including status, progress, timestamps, and the completed video URL. Use this endpoint after you create a Vidu video task. It returns the task state and includes `video_url` after the task is completed. ## Check these fields * `status` tells you whether the task is `queued`, `in_progress`, `completed`, `failed`, or `error`. * `progress` is a coarse completion percentage. * `video_url` appears on completed responses. * `error` appears when a task fails. ## Polling flow Start with [Create a Vidu video](./create) and store the returned `id`. Send the task ID to this endpoint until `status` reaches `completed`, `failed`, or `error`. When `status` is `completed`, call [Retrieve Vidu video content](./retrieve-content). # Create a Wan video Source: https://apidoc.cometapi.com/api/video/wan/create api/openapi/video/wan/post-create.openapi.json POST /v1/videos Create a Wan text-to-video or image-to-video task through CometAPI with POST /v1/videos, then poll the task and download the completed MP4 file. Use this endpoint to create a Wan text-to-video or image-to-video task. The API returns a task ID immediately, so store the returned `id` and poll the task until it reaches a terminal status. `POST /v1/videos` uses `multipart/form-data`. Send scalar controls as form fields and reference images as `input_reference` file fields. ## Choose an input mode | Goal | Required fields | Optional fields | | -------------- | --------------------------------------------- | ----------------- | | Text-to-video | `model`, `prompt` | `seconds`, `size` | | Image-to-video | `model`, `prompt`, one `input_reference` file | `seconds`, `size` | To confirm a Wan model ID that is available to your API key, use [List available models](/guides/how-to-list-available-models). ## Use reference images For image-to-video, upload one reference image through the `input_reference` multipart field. The file can be up to 20 MB. The image guides the composition and appearance of the generated video. Use the prompt to describe motion, camera behavior, and details that the video should preserve. ## Set duration and size | Model ID | `seconds` | Default | | -------- | ---------------- | ------------------------ | | `wan2.7` | integer `2`-`15` | `5` seconds, `1920x1080` | | `wan2.6` | `5`, `10`, `15` | `5` seconds, `1920x1080` | Set `size` to one of the WxH values below for the target model. ### Wan 2.7 size values | Resolution tier | Aspect ratio | `size` (`WxH`) | | --------------- | ------------ | -------------- | | `720p` | `16:9` | `1280x720` | | | `9:16` | `720x1280` | | `1080p` | `16:9` | `1920x1080` | | | `9:16` | `1080x1920` | | | `1:1` | `1440x1440` | ### Wan 2.6 size values | Resolution tier | Aspect ratio | `size` (`WxH`) | | --------------- | ------------ | -------------- | | `720p` | `16:9` | `1280x720` | | | `9:16` | `720x1280` | | | `4:3` | `1088x832` | | | `3:4` | `832x1088` | | `1080p` | `16:9` | `1920x1080` | | | `9:16` | `1080x1920` | | | `1:1` | `1440x1440` | | | `4:3` | `1632x1248` | | | `3:4` | `1248x1632` | ## Task flow Send the multipart form request and store the returned `id`. Call [Retrieve a Wan video](./retrieve) until `status` is `completed`, `failed`, or `error`. When the task is `completed`, call [Retrieve Wan video content](./retrieve-content) to download the MP4 file. # Retrieve a Wan video Source: https://apidoc.cometapi.com/api/video/wan/retrieve api/openapi/video/wan/get-retrieve.openapi.json GET /v1/videos/{task_id} Retrieve a Wan video task by task ID, including status, progress, timestamps, and the completed video URL. Use this endpoint after you create a Wan video task. It returns the task state and includes `video_url` after the task is completed. ## Check these fields * `status` tells you whether the task is `queued`, `in_progress`, `completed`, `failed`, or `error`. * `progress` is a coarse completion percentage. * `video_url` appears on completed responses. * `error` appears when a task fails. ## Polling flow Start with [Create a Wan video](./create) and store the returned `id`. Send the task ID to this endpoint until `status` reaches `completed`, `failed`, or `error`. When `status` is `completed`, call [Retrieve Wan video content](./retrieve-content). # Download Wan video content Source: https://apidoc.cometapi.com/api/video/wan/retrieve-content api/openapi/video/wan/get-retrieve-content.openapi.json GET /v1/videos/{task_id}/content Download the completed MP4 file for a Wan video task through the content route. Use this endpoint to download the MP4 file for a completed Wan video task. If the task is still running, the API returns a JSON error instead of video bytes. ## Before you download * Create a task with [Create a Wan video](./create). * Poll with [Retrieve a Wan video](./retrieve) until `status` is `completed`. * Pass the same task ID to this endpoint. ## Store completed media The response body is binary `video/mp4` content. Save the bytes to your own storage when your application needs durable access to the generated media. # Get xAI video results Source: https://apidoc.cometapi.com/api/video/xai/get-video-generation-results api/openapi/video/xai/get-get-video-generation-results.openapi.json GET /grok/v1/videos/{request_id} Use GET /grok/v1/videos/{request_id} to poll xAI video generation status and retrieve the final video URL once processing completes. Use this endpoint after you already have a `request_id`. It tells you whether the xAI job is still running and returns the final video metadata when ready. ## Check these fields first * `request_id` when the task has been accepted but the result is not ready yet * `status` for the xAI job state; keep polling until it reaches `done` * `progress` for completion percentage when it is returned * `video.url` when the render is complete ## Polling loop Start with [Create an xAI video](./video-generation) or [Create an xAI video edit](./video-edit), then copy the returned `request_id`. If the response only echoes `request_id`, wait a few seconds and poll again. Once `status` appears, use it as the stop condition. Download or copy the final `video.url` promptly, because xAI documents generated URLs as temporary. # Create an xAI video edit Source: https://apidoc.cometapi.com/api/video/xai/video-edit api/openapi/video/xai/post-video-edit.openapi.json POST /grok/v1/videos/edits Use POST /grok/v1/videos/edits to edit a source video with a text prompt, preserve motion, and get a request_id for async polling results. Use this endpoint to edit an existing MP4 with a text instruction. The output stays closer to the source clip's timing and composition than a fresh generation request. ## Before you send the request * Provide a reachable `video.url` * Keep the source clip short; xAI's own guidance caps edits at about 8.7 seconds * Use a focused instruction that describes one clear change * Save the returned `request_id`, because edits use the same polling flow as generation ## Editing flow Send the source video URL, edit prompt, and `model: grok-imagine-video`. Call [Get xAI video results](./get-video-generation-results) until the job is finished. Download the finished output or move the returned URL into your own storage pipeline. ## What changes on CometAPI xAI documents video editing as the same async lifecycle as generation, just with a source video instead of an optional source image. CometAPI keeps that behavior and the same polling endpoint, so your edit workflow is still start -> poll -> download. # Create an xAI video Source: https://apidoc.cometapi.com/api/video/xai/video-generation api/openapi/video/xai/post-video-generation.openapi.json POST /grok/v1/videos/generations Use CometAPI POST /grok/v1/videos/generations to create Grok image-to-video jobs from an input image and prompt, then poll results via request_id. Use this endpoint to start a Grok image-to-video job from one source image and a prompt. It returns a `request_id` immediately, so treat it as the first step in an async workflow. ## Start with a small request * Use `model: grok-imagine-video-1.5` * Set `image.url` to a public JPEG, PNG, or WebP URL * For a first request, keep `duration` at `1` and `resolution` at `720p` * Keep `prompt` explicit so the animation direction is clear * If you send base64, keep the docs and OpenAPI example form as `data:image/png;base64,` ## Duration and resolution | Setting | Supported values | Default | Boundary behavior | | -------------- | --------------------------------------------- | ---------------------- | ----------------------------------------------------------------------------------------------------------------- | | `duration` | integer `1`-`15` | `8` | Use shorter clips for first tests; longer clips cost more and take longer to complete. | | `resolution` | `480p`, `720p`, `1080p` | `720p` in the examples | Higher resolution requests cost more and take longer to complete. | | `aspect_ratio` | ratio labels such as `1:1`, `16:9`, or `9:16` | `16:9` in the examples | This endpoint uses `resolution` plus `aspect_ratio`; do not send a separate `size` field for exact `WxH` control. | | Request combination | Intended output `WxH` | | ---------------------------------------- | --------------------- | | `resolution: 480p`, `aspect_ratio: 1:1` | `480x480` | | `resolution: 720p`, `aspect_ratio: 16:9` | `1280x720` | | `resolution: 720p`, `aspect_ratio: 9:16` | `720x1280` | ## Task flow Send the prompt and source image, then save the returned `request_id`. Call [Get xAI video results](./get-video-generation-results) until the nested provider status becomes `done`. Copy the final `video.url` into your own storage if you need it after the provider's temporary delivery window. # Handle error codes Source: https://apidoc.cometapi.com/errors/error-codes-handling Use this guide to classify CometAPI error responses and apply retry or fix steps for common request failures. CometAPI error handling is easiest when you separate **request-shape problems**, **auth problems**, **path mistakes**, and **retryable platform failures**. Use the combination of HTTP status, `error.code`, and `error.message` to decide whether to fix the request or retry it. ## Quick triage | Status | What it usually means | Retry? | First action | | ---------------------------------------- | --------------------------------------------------------------------------------------------------------------------- | ---------- | -------------------------------------------------------------------------------------------- | | `400` | Request validation failed before the request was processed normally. | No | Validate `model`, `messages`, JSON shape, and field types. | | `401` | API key is missing, malformed, or invalid. | No | Check `Authorization: Bearer $COMETAPI_KEY`. | | `403` | Access was blocked or the current request was not allowed. | Usually no | Retry with a known-good request and remove model-specific fields first. | | Path mistake | Wrong base URL or wrong endpoint path. On Comet this may show up as a `301` redirect or HTML, not a clean JSON `404`. | No | Use `https://api.cometapi.com/v1` exactly and disable auto-follow redirects while debugging. | | `429` | Rate limiting or temporary saturation. | Yes | Use exponential backoff with jitter. | | `500` with `error.code: invalid_request` | A malformed request surfaced through a server-status response. | No | Fix the request body before retrying. | | `500`, `503`, `504`, `524` | Platform, provider, or timeout-class failure. | Yes | Retry with backoff and keep the request id. | ## Error envelope Many CometAPI failures use an error body like this: ```json theme={null} { "error": { "message": "...", "type": "comet_api_error", "param": "", "code": "invalid_request" } } ``` Some responses leave `code` empty. When the status is `500`, treat `error.code` and `error.message` as the deciding signal. ## `400 Bad Request` A `400` usually means the request body failed validation before the request could be processed normally. Common causes: * Missing required fields such as `model` * Invalid JSON shape * Sending a field with the wrong type * Reusing provider-specific parameters that the selected endpoint does not accept Start from a minimal known-good request, then add optional fields back one by one. Compare the payload against the endpoint schema in the API reference. Use a minimal request like this: ```json theme={null} { "model": "your-model-id", "messages": [ { "role": "user", "content": "Hello" } ] } ``` Replace `your-model-id` with any current model ID from the [CometAPI Models page](/overview/models). Do not assume every malformed chat request returns `400`. Missing required chat fields such as `messages` can also surface as `500` with `error.code: invalid_request`. ## `500 Internal Server Error` Most `500` responses indicate a platform or provider failure. For Chat Completions, some malformed requests can also surface as `500` while still carrying `error.code: invalid_request`. One example is a request that omits `messages`: ```json theme={null} { "error": { "message": "field messages is required (request id: ...)", "type": "comet_api_error", "param": "", "code": "invalid_request" } } ``` If a `500` response has `error.code: invalid_request`, treat it as a request problem: 1. Fix the request body. 2. Compare the payload against the endpoint schema. 3. Retry only after correcting the payload. If a `500` response does not point to an invalid request, keep the `request id` and use backoff. ## `401 Invalid Token` A token failure usually looks like this: ```json theme={null} { "error": { "code": "", "message": "invalid token (request id: ...)", "type": "comet_api_error" } } ``` What to check: 1. The header must be exactly `Authorization: Bearer $COMETAPI_KEY`. 2. Make sure your app is not loading an old key from `.env`, shell history, or a deployed secret store. 3. If one key fails and another key works on the same request, treat this as a token issue, not an endpoint issue. ## `403 Forbidden` `403` is most often one of these situations: * The request is blocked by a platform-side rule such as WAF filtering * The token or route is not allowed to use the requested model or request shape * The chosen model rejects one of the advanced parameters you passed What to do first: 1. Retry with a very simple text request against a known-good model. 2. Remove advanced fields and provider-specific parameters, then add them back gradually. 3. If the response includes a request id, keep it before contacting support. If the message mentions internal terms such as `group` or `channel`, treat those as routing details, not as the first thing to diagnose from the client side. The practical fix is still to validate the token, model, and request shape first. ## Wrong base URL or wrong path On Comet, a path mistake may surface as: * A redirect * A non-JSON HTML response if your client follows redirects * A parsing error inside your SDK * A request that never reaches the API layer cleanly Use this base URL exactly: ```text theme={null} https://api.cometapi.com/v1 ``` Recommended checks: 1. Confirm the base URL includes `/v1`. 2. Confirm the endpoint path matches the documentation exactly. 3. Disable automatic redirect following while debugging path problems. ## `413 Request Entity Too Large` If you see `413`, treat it as a **request size** problem first. Common suspects are: * Large base64 payloads * Oversized images or audio embedded inline * Very large multipart or JSON bodies What to do: 1. Reduce or compress attached content. 2. Split large jobs into smaller requests. 3. Do not assume plain text length is the only cause. ## `429 Too Many Requests` Treat `429` as retryable: 1. Use exponential backoff with jitter. 2. Reduce burst concurrency. 3. Keep request logging on so you can see which route and model are saturating first. For a reusable retry pattern, see the backoff example on [Chat Completions](/api/text/chat). ## `503`, `504`, and `524` These statuses are **server-side or timeout-class failures**. Practical guidance: * `503`: route or provider service temporarily unavailable * `504` and `524`: timeout-class failures between the platform, edge, or provider service What to do: 1. Retry with backoff. 2. Keep the `request id`, endpoint, model, and timestamp. 3. If the same failure repeats across multiple retries, contact support with that context. ## Before you contact support Capture these details first: * HTTP method * Endpoint path * Model ID * **Sanitized request body JSON** (this is the single most useful item for most API calls) * Query parameters if the failing request used them * Exact response body if your client captured it * Full HTTP status * The exact `error.message` * Any `request id` * Approximate timestamp * Whether the same request works with another model or another token If the failing route accepts **file uploads** (image editing, audio upload, video generation, etc.) instead of a plain JSON body, send the equivalent submitted payload: * Field names and text values you sent alongside the file * File name, file type, and approximate file size * Whether the file was uploaded directly, referenced by URL, or embedded as base64 The most effective way to reproduce a bug is the exact sanitized request payload. For most API calls, that means the **raw request body JSON**. For file-upload routes, that means the field list plus file metadata. This shortens support turnaround significantly. # Change the base URL to CometAPI Source: https://apidoc.cometapi.com/guides/change-base-url-to-cometapi Route an OpenAI-compatible client or direct HTTP request to CometAPI by setting the base URL to https://api.cometapi.com/v1. Change the base URL to `https://api.cometapi.com/v1` when you use OpenAI-compatible SDKs or endpoints. Keep the endpoint path and request body format from the API reference, then use your CometAPI API key. ## Use the correct base URL The OpenAI-compatible base URL is: ```text theme={null} https://api.cometapi.com/v1 ``` ## Python base URL The following Python example changes only the client configuration: ```python theme={null} import os from openai import OpenAI client = OpenAI( api_key=os.environ["COMETAPI_KEY"], base_url="https://api.cometapi.com/v1", ) ``` ## Node.js base URL The following Node.js example sets the CometAPI base URL: ```javascript theme={null} import OpenAI from "openai"; const client = new OpenAI({ apiKey: process.env.COMETAPI_KEY, baseURL: "https://api.cometapi.com/v1", }); ``` ## Test the change The following request verifies that the base URL and API key work: ```bash theme={null} curl https://api.cometapi.com/v1/chat/completions \ -H "Authorization: Bearer $COMETAPI_KEY" \ -H "Content-Type: application/json" \ -d '{ "model": "your-model-id", "messages": [ { "role": "user", "content": "Say hello in one sentence." } ] }' ``` A successful response returns a chat completion object: ```json theme={null} { "object": "chat.completion", "choices": [ { "message": { "role": "assistant", "content": "Hello from CometAPI." } } ] } ``` ## Common errors | Error | Fix | | ---------------------------- | ---------------------------------------------------------------------------------------- | | `404` | Include `/v1` in the base URL for OpenAI-compatible endpoints. | | HTML instead of JSON | Check whether your HTTP client followed a redirect from a wrong path. | | `401` | Use `Authorization: Bearer $COMETAPI_KEY`. | | Management API auth mismatch | API key management endpoints use a personal access value, not bearer model-request auth. | ## Related links * [CometAPI quickstart](/overview/quick-start) * [Important guidelines](/overview/important-guidelines) * [Error Codes & Handling](/errors/error-codes-handling) * [Models page](/overview/models) * [Model directory](https://www.cometapi.com/models/) * [Pricing](https://www.cometapi.com/pricing/) # Handle API errors and retries with CometAPI Source: https://apidoc.cometapi.com/guides/error-codes-and-retry-strategy Handle CometAPI errors by separating request-shape problems, authentication failures, rate limits, and retryable platform failures. Handle CometAPI errors by deciding whether the request should be fixed or retried. Retry `429`, timeout-class failures, and temporary server failures with backoff; do not retry malformed requests or authentication failures. ## Retry only retryable failures | Status or signal | Retry? | Action | | ---------------------------- | ---------- | -------------------------------------------------- | | `400` | No | Fix the request body or parameters. | | `401` | No | Fix the API key and `Authorization` header. | | `403` | Usually no | Remove unsupported fields and verify model access. | | `429` | Yes | Retry with exponential backoff and jitter. | | `500` with `invalid_request` | No | Fix the request shape. | | `500`, `503`, `504`, `524` | Yes | Retry with backoff and keep the request ID. | ## Add backoff The following Python example retries only retryable failures: ```python theme={null} import os import random import time from openai import APIError, OpenAI, RateLimitError client = OpenAI( api_key=os.environ["COMETAPI_KEY"], base_url="https://api.cometapi.com/v1", ) for attempt in range(5): try: response = client.chat.completions.create( model="your-model-id", messages=[{"role": "user", "content": "Say hello."}], ) print(response.choices[0].message.content) break except RateLimitError: delay = min(30, 2**attempt) + random.random() time.sleep(delay) except APIError as error: status_code = getattr(error, "status_code", None) if status_code in {500, 503, 504, 524}: delay = min(30, 2**attempt) + random.random() time.sleep(delay) continue raise else: raise RuntimeError("The request failed after retries.") ``` The successful response includes the model output: ```json theme={null} { "choices": [ { "message": { "role": "assistant", "content": "Hello." } } ], "usage": { "total_tokens": 9 } } ``` ## Log useful context The following JSON shape is safe to store after you remove user secrets and large files: ```json theme={null} { "method": "POST", "path": "/v1/chat/completions", "model": "your-model-id", "status": 429, "request_id": "request_id_from_error_message", "retryable": true } ``` ## Common errors | Error | Fix | | --------------------------- | --------------------------------------------------------- | | Retrying `401` | Stop retries and rotate or reload the API key. | | Retrying invalid JSON | Validate the request body before sending another request. | | No request ID in logs | Capture the exact error body before your SDK wraps it. | | Immediate retry after `429` | Add jitter and reduce concurrency. | ## Related links * [Error Codes & Handling](/errors/error-codes-handling) * [Rate limits and concurrency](/guides/rate-limits-and-concurrency) * [Models page](/overview/models) * [Model directory](https://www.cometapi.com/models/) * [Pricing](https://www.cometapi.com/pricing/) * [CometAPI quickstart](/overview/quick-start) # Estimate request cost before calling a model Source: https://apidoc.cometapi.com/guides/how-to-estimate-cost-before-calling-a-model Estimate CometAPI request cost before a model call by combining model directory pricing with input size, output limits, or task count. Estimate cost before a model call by combining the model directory price with the units that the endpoint bills: tokens, images, audio length, or video tasks. Treat the estimate as a budget guard, then use actual usage and billing records after the request completes. ## Estimate token-based calls The following Python example estimates token-based request cost from configured pricing values: ```python theme={null} import math import os prompt = "Write a short product description for CometAPI." max_output_tokens = 200 input_price_per_1m = float(os.environ["MODEL_INPUT_PRICE_PER_1M"]) output_price_per_1m = float(os.environ["MODEL_OUTPUT_PRICE_PER_1M"]) estimated_input_tokens = math.ceil(len(prompt) / 4) estimated_cost = ( estimated_input_tokens * input_price_per_1m + max_output_tokens * output_price_per_1m ) / 1_000_000 print(f"Estimated maximum cost: ${estimated_cost:.6f}") ``` The result is a pre-call estimate: ```text theme={null} Estimated maximum cost: $0.000123 ``` ## Set a maximum output budget The following request caps generated output so the estimate has an upper bound: ```bash theme={null} curl https://api.cometapi.com/v1/chat/completions \ -H "Authorization: Bearer $COMETAPI_KEY" \ -H "Content-Type: application/json" \ -d '{ "model": "your-model-id", "messages": [ { "role": "user", "content": "Write a short product description for CometAPI." } ], "max_completion_tokens": 200 }' ``` The response includes actual usage after the model call: ```json theme={null} { "usage": { "prompt_tokens": 10, "completion_tokens": 42, "total_tokens": 52 } } ``` ## Estimate task-based calls The following JavaScript example estimates a task-based workflow such as image or video generation: ```javascript theme={null} const taskCount = 3; const pricePerTask = Number(process.env.MODEL_PRICE_PER_TASK); const estimatedCost = taskCount * pricePerTask; console.log(`Estimated maximum cost: $${estimatedCost.toFixed(4)}`); ``` The result is the task budget: ```text theme={null} Estimated maximum cost: $0.4500 ``` ## Common errors | Error | Fix | | ---------------------------------- | --------------------------------------------------------------------------------------------------- | | Using a price from the wrong model | Copy pricing from the same model ID in the model directory. | | Ignoring output tokens | Set `max_completion_tokens` or the endpoint-specific output limit. | | Treating estimates as invoices | Compare estimates with actual usage after the call. | | Missing task multipliers | For image, audio, and video, check whether billing is per task, per second, or per generated asset. | ## Related links * [Pricing](https://www.cometapi.com/pricing/) * [Model directory](https://www.cometapi.com/models/) * [Models page](/overview/models) * [About Pricing](/pricing/about-pricing) * [CometAPI quickstart](/overview/quick-start) # List available CometAPI models Source: https://apidoc.cometapi.com/guides/how-to-list-available-models List available CometAPI models with the model catalog endpoint and use the model directory to confirm capabilities and pricing. List available models by calling the public `GET /api/models` catalog endpoint. Use the returned model IDs for API requests, then confirm capability and pricing details in the model directory. ## Call the model catalog The following request lists available models: ```bash theme={null} curl https://api.cometapi.com/api/models ``` The response contains model records: ```json theme={null} { "success": true, "page": 0, "page_size": 0, "total": 301, "data": [ { "id": "gpt-image-2", "provider": "OpenAI", "model_type": "image", "features": [ "text-to-image" ], "pricing": { "currency": "USD / M Tokens", "input": 4, "output": 24, "per_request": null, "per_second": null }, "api_doc_url": "https://apidoc.cometapi.com/api/image/openai/images" } ] } ``` ## Python model list The following Python example prints model IDs from the catalog: ```python theme={null} import requests response = requests.get("https://api.cometapi.com/api/models", timeout=30) response.raise_for_status() models = response.json()["data"] for model in models: print(model["id"]) ``` The output is a list of model IDs: ```text theme={null} your-model-id another-model-id ``` ## Use a model ID The following example sends a request with one model ID from the catalog: ```bash theme={null} curl https://api.cometapi.com/v1/chat/completions \ -H "Authorization: Bearer $COMETAPI_KEY" \ -H "Content-Type: application/json" \ -d '{ "model": "your-model-id", "messages": [ { "role": "user", "content": "Say hello." } ] }' ``` The response uses the selected model ID: ```json theme={null} { "model": "your-model-id", "choices": [ { "message": { "role": "assistant", "content": "Hello." } } ] } ``` ## Common errors | Error | Fix | | ---------------------------------------- | ----------------------------------------------------------------------------------------------------------------------------------- | | Treating the catalog as pricing data | Use the model directory for pricing and capability details. | | Reusing stale model IDs | Fetch the catalog during deployment or startup. | | Confusing `/api/models` and `/v1/models` | Use `/api/models` for the public catalog. Use authenticated `/v1/models` only when you need the OpenAI-compatible model-list shape. | | Wrong endpoint for the model type | Match the model capability to the API reference page. | ## Related links * [Models page](/overview/models) * [Model directory](https://www.cometapi.com/models/) * [Pricing](https://www.cometapi.com/pricing/) * [Text Models](/api/text) * [Image Models](/api/image) * [Video Models](/api/video) * [Audio Models](/api/audio) # Use CometAPI docs with LLMs Source: https://apidoc.cometapi.com/guides/how-to-use-cometapi-docs-with-llms Use CometAPI llms.txt and llms-full.txt with coding assistants, retrieval systems, and model prompts. Use `llms.txt` when you need a compact index of CometAPI documentation pages. Use `llms-full.txt` when your tool can ingest the full documentation text for retrieval, question answering, or coding assistance. ## Fetch the compact index The following request downloads the CometAPI `llms.txt` index: ```bash theme={null} curl https://apidoc.cometapi.com/llms.txt ``` The response starts with the documentation title and linked page list: ```text theme={null} # CometAPI Documentation > CometAPI developer documentation for unified API access... ## Docs - [Create a new API key](https://apidoc.cometapi.com/api/api-keys/create-api-key.md) ``` ## Fetch the full text The following request downloads the full text export: ```bash theme={null} curl https://apidoc.cometapi.com/llms-full.txt ``` The response contains page content grouped by source URL: ```text theme={null} # Create a new API key Source: https://apidoc.cometapi.com/api/api-keys/create-api-key Create a new CometAPI API key for the authenticated account. ``` ## Add docs to a retrieval job The following Python example downloads the full text and writes it to a local file for indexing: ```python theme={null} from pathlib import Path import requests url = "https://apidoc.cometapi.com/llms-full.txt" response = requests.get(url, timeout=60) response.raise_for_status() Path("cometapi-docs.txt").write_text(response.text, encoding="utf-8") print(len(response.text)) ``` The result is the number of characters saved. This is example output only; your value will differ whenever the documentation changes: ```text theme={null} 449946 ``` ## Common errors | Error | Fix | | -------------------------- | ------------------------------------------------------------------- | | Tool context is too small | Use `llms.txt` first, then fetch only the linked pages that matter. | | Full text is too large | Chunk `llms-full.txt` by heading or source URL before indexing. | | Broken local cache | Refresh the file during your documentation sync job. | | Missing page in AI results | Confirm that the page appears in navigation and in `llms.txt`. | ## Related links * [CometAPI docs home](/) * [Models page](/overview/models) * [Model directory](https://www.cometapi.com/models/) * [Pricing](https://www.cometapi.com/pricing/) * [CometAPI quickstart](/overview/quick-start) # Build model and provider fallback with CometAPI Source: https://apidoc.cometapi.com/guides/model-fallback-with-cometapi Keep CometAPI as the primary route, switch models inside CometAPI first, and use an official provider as an optional final fallback. Build two fallback layers for text requests. Keep CometAPI as the primary route. First, change the model ID inside CometAPI. If those routes fail and official fallback is enabled, call the matching official provider. Keep the same CometAPI API key and base URL. Try a compatible secondary model ID after the primary model fails. Use a separate OpenAI or Anthropic client, API key, model ID, account, and billing configuration. The recommended order is `CometAPI primary model → CometAPI fallback model → matching official provider`. ## Decide when to fallback Use a narrow error policy so that fallback does not hide request problems: | Failure | Use the next route? | | ----------------------------------------------------------- | --------------------------------------------------------- | | Connection error, timeout, `408`, `429`, or temporary `5xx` | Yes. Try the next configured route. | | Verified model-unavailable, balance, or quota signal | Add that exact signal to the classifier before you use it | | Invalid request, invalid API key, or unsupported parameter | No. Fix the request or configuration. | The examples below use `ENABLE_OFFICIAL_FALLBACK` as the explicit switch. If you also fallback on a model or account limit, add only its verified error signal to your application's error classifier. Install `openai` and `anthropic` for Python, or install `openai` and `@anthropic-ai/sdk` for Node.js. Then configure these environment variables: * **OpenAI route:** `COMETAPI_KEY`, `COMETAPI_OPENAI_PRIMARY_MODEL`, `COMETAPI_OPENAI_FALLBACK_MODEL`, `OPENAI_API_KEY`, and `OPENAI_OFFICIAL_MODEL` * **Claude route:** `COMETAPI_KEY`, `COMETAPI_CLAUDE_PRIMARY_MODEL`, `COMETAPI_CLAUDE_FALLBACK_MODEL`, `ANTHROPIC_API_KEY`, and `ANTHROPIC_OFFICIAL_MODEL` * **Shared controls:** `ENABLE_OFFICIAL_FALLBACK` and `ROUTE_TIMEOUT_MS` `ENABLE_OFFICIAL_FALLBACK` defaults to `false`. Set it to `true` only when the official-provider account is ready. `ROUTE_TIMEOUT_MS` is the timeout for each attempt and defaults to 30 seconds. Set it from your application's latency budget; total fallback time can include all three attempts. Choose fallback models that support the same request format and the capabilities that your application requires. Test every route before you depend on it. Official-provider requests use a separate account and billing configuration. Configure provider budgets and alerts before you enable this route. Record the official fallback rate so that you can investigate sustained usage. ## Implement the fallback chain Choose the tab that matches the request format that your application uses. Configure separate model IDs for the CometAPI and official-provider routes. Use Chat Completions for both CometAPI and the OpenAI official API. The request shape stays the same, but each route has its own client, API key, and model ID. ```python Python theme={null} import os from openai import APIError, OpenAI official_fallback_enabled = ( os.getenv("ENABLE_OFFICIAL_FALLBACK", "false").lower() == "true" ) route_timeout = int(os.getenv("ROUTE_TIMEOUT_MS", "30000")) / 1000 cometapi = OpenAI( api_key=os.environ["COMETAPI_KEY"], base_url="https://api.cometapi.com/v1", max_retries=0, timeout=route_timeout, ) routes = [ ( "cometapi-primary", cometapi, os.environ["COMETAPI_OPENAI_PRIMARY_MODEL"], ), ( "cometapi-fallback", cometapi, os.environ["COMETAPI_OPENAI_FALLBACK_MODEL"], ), ] if official_fallback_enabled: routes.append( ( "openai-official", OpenAI( api_key=os.environ["OPENAI_API_KEY"], base_url="https://api.openai.com/v1", max_retries=0, timeout=route_timeout, ), os.environ["OPENAI_OFFICIAL_MODEL"], ) ) def should_fallback(error: APIError) -> bool: status = getattr(error, "status_code", None) code = getattr(error, "code", None) return ( status is None or status in {408, 429} or ( status >= 500 and code not in {"invalid_request", "invalid_request_error"} ) ) def complete(messages: list[dict]) -> dict: for index, (route, client, model) in enumerate(routes): try: response = client.chat.completions.create( model=model, messages=messages, ) return { "text": response.choices[0].message.content, "route": route, "model": model, } except APIError as error: if index == len(routes) - 1 or not should_fallback(error): raise raise RuntimeError("No fallback route completed.") result = complete( [{"role": "user", "content": "Summarize CometAPI in one sentence."}] ) print(result) ``` ```javascript Node.js theme={null} import OpenAI from "openai"; function requiredEnv(name) { const value = process.env[name]; if (!value) { throw new Error(`${name} is required.`); } return value; } const officialFallbackEnabled = process.env.ENABLE_OFFICIAL_FALLBACK === "true"; const routeTimeout = Number(process.env.ROUTE_TIMEOUT_MS ?? 30000); const cometapi = new OpenAI({ apiKey: requiredEnv("COMETAPI_KEY"), baseURL: "https://api.cometapi.com/v1", maxRetries: 0, timeout: routeTimeout, }); const routes = [ { route: "cometapi-primary", client: cometapi, model: requiredEnv("COMETAPI_OPENAI_PRIMARY_MODEL"), }, { route: "cometapi-fallback", client: cometapi, model: requiredEnv("COMETAPI_OPENAI_FALLBACK_MODEL"), }, ]; if (officialFallbackEnabled) { routes.push({ route: "openai-official", client: new OpenAI({ apiKey: requiredEnv("OPENAI_API_KEY"), baseURL: "https://api.openai.com/v1", maxRetries: 0, timeout: routeTimeout, }), model: requiredEnv("OPENAI_OFFICIAL_MODEL"), }); } function shouldFallback(error) { if (!(error instanceof OpenAI.APIError)) { throw error; } return ( error.status === undefined || error.status === 408 || error.status === 429 || (error.status >= 500 && !["invalid_request", "invalid_request_error"].includes(error.code)) ); } async function complete(messages) { for (const [index, { route, client, model }] of routes.entries()) { try { const response = await client.chat.completions.create({ model, messages, }); return { text: response.choices[0].message.content, route, model, }; } catch (error) { if (index === routes.length - 1 || !shouldFallback(error)) { throw error; } } } throw new Error("No fallback route completed."); } const result = await complete([ { role: "user", content: "Summarize CometAPI in one sentence." }, ]); console.log(result); ``` If your application uses the Responses API, keep the same dual-client routing pattern and adapt the request and response fields. See the official [Chat Completions reference](https://developers.openai.com/api/reference/resources/chat/subresources/completions/methods/create). Use the Anthropic Messages request format for both CometAPI and the Anthropic official API. This avoids converting between OpenAI-compatible messages and Anthropic content blocks during fallback. ```python Python theme={null} import os import anthropic official_fallback_enabled = ( os.getenv("ENABLE_OFFICIAL_FALLBACK", "false").lower() == "true" ) route_timeout = int(os.getenv("ROUTE_TIMEOUT_MS", "30000")) / 1000 cometapi = anthropic.Anthropic( api_key=os.environ["COMETAPI_KEY"], auth_token=None, base_url="https://api.cometapi.com", max_retries=0, timeout=route_timeout, ) routes = [ ( "cometapi-primary", cometapi, os.environ["COMETAPI_CLAUDE_PRIMARY_MODEL"], ), ( "cometapi-fallback", cometapi, os.environ["COMETAPI_CLAUDE_FALLBACK_MODEL"], ), ] if official_fallback_enabled: routes.append( ( "anthropic-official", anthropic.Anthropic( api_key=os.environ["ANTHROPIC_API_KEY"], auth_token=None, base_url="https://api.anthropic.com", max_retries=0, timeout=route_timeout, ), os.environ["ANTHROPIC_OFFICIAL_MODEL"], ) ) def should_fallback(error: anthropic.APIError) -> bool: status = getattr(error, "status_code", None) body = getattr(error, "body", {}) or {} details = body.get("error", {}) if isinstance(body, dict) else {} code = details.get("code") or details.get("type") return ( status is None or status in {408, 429} or ( status >= 500 and code not in {"invalid_request", "invalid_request_error"} ) ) def text_from_message(message) -> str: return "".join( block.text for block in message.content if block.type == "text" ) def complete(messages: list[dict]) -> dict: for index, (route, client, model) in enumerate(routes): try: response = client.messages.create( model=model, max_tokens=512, messages=messages, ) return { "text": text_from_message(response), "route": route, "model": model, } except anthropic.APIError as error: if index == len(routes) - 1 or not should_fallback(error): raise raise RuntimeError("No fallback route completed.") result = complete( [{"role": "user", "content": "Summarize CometAPI in one sentence."}] ) print(result) ``` ```javascript Node.js theme={null} import Anthropic from "@anthropic-ai/sdk"; function requiredEnv(name) { const value = process.env[name]; if (!value) { throw new Error(`${name} is required.`); } return value; } const officialFallbackEnabled = process.env.ENABLE_OFFICIAL_FALLBACK === "true"; const routeTimeout = Number(process.env.ROUTE_TIMEOUT_MS ?? 30000); const cometapi = new Anthropic({ apiKey: requiredEnv("COMETAPI_KEY"), authToken: null, baseURL: "https://api.cometapi.com", maxRetries: 0, timeout: routeTimeout, }); const routes = [ { route: "cometapi-primary", client: cometapi, model: requiredEnv("COMETAPI_CLAUDE_PRIMARY_MODEL"), }, { route: "cometapi-fallback", client: cometapi, model: requiredEnv("COMETAPI_CLAUDE_FALLBACK_MODEL"), }, ]; if (officialFallbackEnabled) { routes.push({ route: "anthropic-official", client: new Anthropic({ apiKey: requiredEnv("ANTHROPIC_API_KEY"), authToken: null, baseURL: "https://api.anthropic.com", maxRetries: 0, timeout: routeTimeout, }), model: requiredEnv("ANTHROPIC_OFFICIAL_MODEL"), }); } function shouldFallback(error) { if (!(error instanceof Anthropic.APIError)) { throw error; } const details = error.error?.error ?? error.error ?? {}; const code = details.code ?? details.type ?? error.type; return ( error.status === undefined || error.status === 408 || error.status === 429 || (error.status >= 500 && !["invalid_request", "invalid_request_error"].includes(code)) ); } function textFromMessage(message) { return message.content .filter((block) => block.type === "text") .map((block) => block.text) .join(""); } async function complete(messages) { for (const [index, { route, client, model }] of routes.entries()) { try { const response = await client.messages.create({ model, max_tokens: 512, messages, }); return { text: textFromMessage(response), route, model, }; } catch (error) { if (index === routes.length - 1 || !shouldFallback(error)) { throw error; } } } throw new Error("No fallback route completed."); } const result = await complete([ { role: "user", content: "Summarize CometAPI in one sentence." }, ]); console.log(result); ``` For the complete request and response format, see the official [Anthropic Messages reference](https://platform.claude.com/docs/en/api/messages/create). ## Switch between model families GPT and Claude can fallback to each other when your application converts both requests to shared fields, normalizes both responses, and verifies the required capabilities on every route. A model ID change alone is not enough when request or response shapes differ. ## Related links * [Error codes and retry strategy](/guides/error-codes-and-retry-strategy) * [Chat Completions](/api/text/chat) * [Anthropic Messages](/api/text/anthropic-messages) * [Models page](/overview/models) * [Pricing](https://www.cometapi.com/pricing/) # Handle rate limits and concurrency Source: https://apidoc.cometapi.com/guides/rate-limits-and-concurrency Handle CometAPI rate limits by capping request concurrency, retrying 429 responses with jitter, and monitoring usage by model and route. Handle rate limits by controlling concurrency before requests leave your app. When CometAPI returns `429`, retry with exponential backoff and jitter, then lower burst traffic if repeated retries occur. ## Limit concurrency The following Python example caps concurrent chat requests with an async semaphore: ```python theme={null} import asyncio import os from openai import AsyncOpenAI client = AsyncOpenAI( api_key=os.environ["COMETAPI_KEY"], base_url="https://api.cometapi.com/v1", ) semaphore = asyncio.Semaphore(5) async def ask(prompt): async with semaphore: completion = await client.chat.completions.create( model="your-model-id", messages=[{"role": "user", "content": prompt}], ) return completion.choices[0].message.content async def main(): prompts = ["Say hello.", "Write a title.", "Return one JSON key."] results = await asyncio.gather(*(ask(prompt) for prompt in prompts)) print(results) asyncio.run(main()) ``` The result is an array of model outputs: ```json theme={null} [ "Hello.", "A concise title", "{\"key\":\"value\"}" ] ``` ## Retry rate limits The following JavaScript example retries `429` responses with jitter: ```javascript theme={null} import OpenAI from "openai"; const client = new OpenAI({ apiKey: process.env.COMETAPI_KEY, baseURL: "https://api.cometapi.com/v1", }); async function sleep(milliseconds) { return new Promise((resolve) => setTimeout(resolve, milliseconds)); } async function createCompletion() { for (let attempt = 0; attempt < 5; attempt += 1) { try { return await client.chat.completions.create({ model: "your-model-id", messages: [{ role: "user", content: "Say hello." }], }); } catch (error) { if (error.status !== 429 || attempt === 4) { throw error; } const delay = Math.min(30000, 1000 * 2 ** attempt); await sleep(delay + Math.random() * 1000); } } } const completion = await createCompletion(); console.log(completion.choices[0].message.content); ``` The successful response contains a normal chat completion: ```json theme={null} { "choices": [ { "message": { "content": "Hello." } } ] } ``` ## Common errors | Error | Fix | | --------------------------- | ---------------------------------------------------------- | | Unlimited parallel requests | Add a semaphore, queue, or worker pool. | | Retrying all failures | Retry only `429` and temporary server failures. | | No per-model metrics | Log route, model ID, status, and latency for each request. | | Retry storm | Add jitter and cap the maximum retry delay. | ## Related links * [Error codes and retry strategy](/guides/error-codes-and-retry-strategy) * [Error Codes & Handling](/errors/error-codes-handling) * [Models page](/overview/models) * [Model directory](https://www.cometapi.com/models/) * [Pricing](https://www.cometapi.com/pricing/) * [CometAPI quickstart](/overview/quick-start) # Use CometAPI with OpenAI SDKs Source: https://apidoc.cometapi.com/guides/use-cometapi-with-openai-sdk Configure the OpenAI Python and Node.js SDKs for CometAPI by setting the CometAPI API key and base URL. Use the OpenAI SDK with CometAPI by changing two client settings: the API key and the base URL. Keep your existing OpenAI-compatible request code, then replace the model ID with an available CometAPI model ID. ## Install the SDK The following command installs the OpenAI Python SDK: ```bash theme={null} pip install openai ``` The following command installs the OpenAI Node.js SDK: ```bash theme={null} npm install openai ``` ## Python client The following Python example creates a CometAPI client and sends a chat request: ```python theme={null} import os from openai import OpenAI client = OpenAI( api_key=os.environ["COMETAPI_KEY"], base_url="https://api.cometapi.com/v1", ) completion = client.chat.completions.create( model="your-model-id", messages=[ { "role": "user", "content": "Answer in one short sentence: What is CometAPI?", } ], ) print(completion.choices[0].message.content) ``` The response object contains the assistant message: ```json theme={null} { "choices": [ { "message": { "role": "assistant", "content": "CometAPI provides API access to models from multiple providers." }, "finish_reason": "stop" } ], "usage": { "prompt_tokens": 16, "completion_tokens": 12, "total_tokens": 28 } } ``` ## Node.js client The following Node.js example uses `baseURL` with the OpenAI SDK: ```javascript theme={null} import OpenAI from "openai"; const client = new OpenAI({ apiKey: process.env.COMETAPI_KEY, baseURL: "https://api.cometapi.com/v1", }); const completion = await client.chat.completions.create({ model: "your-model-id", messages: [ { role: "user", content: "Answer in one short sentence: What is CometAPI?", }, ], }); console.log(completion.choices[0].message.content); ``` The response shape is the same OpenAI-compatible chat completion shape: ```json theme={null} { "id": "chatcmpl_example", "object": "chat.completion", "choices": [ { "index": 0, "message": { "role": "assistant", "content": "CometAPI provides API access to models from multiple providers." } } ] } ``` ## Common errors | Error | Fix | | ---------------------- | --------------------------------------------------------------------------- | | `401` | Confirm that `COMETAPI_KEY` is set and that the request uses `Bearer` auth. | | SDK still calls OpenAI | Set `base_url` in Python or `baseURL` in Node.js. | | Invalid model ID | Choose a model ID from the [Models page](/overview/models). | | Missing `/v1` | Use `https://api.cometapi.com/v1` for OpenAI-compatible SDKs. | ## Related links * [CometAPI quickstart](/overview/quick-start) * [Chat Completions](/api/text/chat) * [Responses](/api/text/responses) * [Models page](/overview/models) * [Model directory](https://www.cometapi.com/models/) * [Pricing](https://www.cometapi.com/pricing/) * [OpenAI Python SDK](https://github.com/openai/openai-python) * [OpenAI Node.js SDK](https://github.com/openai/openai-node) # Use polling and webhooks for video generation Source: https://apidoc.cometapi.com/guides/webhook-and-polling-for-video-generation Track CometAPI video generation with polling and webhooks by storing task IDs, checking task status, and handling callback delivery failures. Use polling as the baseline for video generation because every async job returns a task ID that you can query. Add webhooks only when the selected video endpoint supports callback URLs, and keep polling as the source of truth for missed or provider-specific callback delivery. ## Create a video task The following request creates a minimal video task and stores the returned ID. Add duration, resolution, or callback fields only when the selected model page documents those fields. ```bash theme={null} curl https://api.cometapi.com/v1/videos \ -H "Authorization: Bearer $COMETAPI_KEY" \ -F "model=doubao-seedance-2-0" \ -F "prompt=A cinematic shot of a paper airplane crossing a desk" ``` The response includes a task ID and status: ```json theme={null} { "id": "task_example", "task_id": "task_example", "object": "video", "model": "doubao-seedance-2-0", "status": "queued", "progress": 0, "created_at": 1779872000 } ``` ## Poll status The following request checks the video task status: ```bash theme={null} curl https://api.cometapi.com/v1/videos/task_example \ -H "Authorization: Bearer $COMETAPI_KEY" ``` The response changes as the task progresses. Completed responses can include `video_url` when the model adapter has a result URL; otherwise use model-specific result fields or the `/v1/videos/{id}/content` content route when that model supports proxied downloads. ```json theme={null} { "id": "task_example", "object": "video", "model": "doubao-seedance-2-0", "status": "completed", "progress": 100, "completed_at": 1779872300, "video_url": "" } ``` ## Receive a webhook CometAPI does not define one universal callback payload for every video model. Treat callbacks as provider-specific pass-through events, store the raw body, and reconcile final state with polling. The following Express handler accepts a video callback and stores the event: ```javascript theme={null} import express from "express"; const app = express(); app.use(express.json({ limit: "2mb" })); app.post("/cometapi/video-webhook", async (request, response) => { const event = request.body; console.log("Task ID:", event.task_id || event.id); console.log("Status:", event.status); response.status(200).json({ received: true }); }); app.listen(3000); ``` A callback payload commonly includes task identity and status fields, but exact nesting depends on the selected model or provider: ```json theme={null} { "task_id": "task_example", "status": "completed", "progress": 100, "result": { "video_url": "https://example.com/result.mp4" } } ``` ## Common errors | Error | Fix | | ---------------------------------- | ---------------------------------------------------------------------------------------------------------------------------- | | Lost callback | Poll by task ID until your app has stored a terminal state. | | Duplicate callback | Make callback handling idempotent by task ID. | | Callback rejected | Return a `2xx` response quickly, then process the job in the background. | | Provider-specific payload mismatch | Store the raw callback payload and normalize it in your app. | | Missing `video_url` | Treat `video_url` as optional and use polling plus model-specific result fields or `/v1/videos/{id}/content` when available. | ## Related links * [Video Models](/api/video) * [Create video](/api/video/sora-2/create) * [Retrieve video](/api/video/sora-2/retrieve) * [Models page](/overview/models) * [Model directory](https://www.cometapi.com/models/) * [Pricing](https://www.cometapi.com/pricing/) # CometAPI Documentation Source: https://apidoc.cometapi.com/index CometAPI docs: quick start, OpenAI-compatible chat completions, plus image, video, and audio APIs for GPT, Claude, Gemini, Nano Banana, GPT Image, Veo, Kling. ## Access top models at low cost Get your free API key and make your first call in minutes. Browse all 500+ models with live pricing. Manage API keys, monitor usage, and track costs. ## Explore by model type **GPT, Claude, Gemini, Grok** and more — through a single chat completions endpoint. Fully OpenAI-compatible; change one line of config. **Nano Banana, GPT Image, Seedream** and more. Control style, lighting, and character consistency across all major providers. **Seedance, HappyHorse, Sora, Veo, Grok, Kling** in one place. Text-to-video, image-to-video, and video extension through a unified API. **Whisper, TTS, Kling TTS** for transcription, translation, and synthesis. Build voice experiences with the familiar OpenAI audio API format. ## Start in minutes CometAPI uses the OpenAI SDK format — change only `base_url` and `api_key`: ```python Python theme={null} import os import openai client = openai.OpenAI( api_key=os.environ["COMETAPI_KEY"], base_url="https://api.cometapi.com/v1" ) response = client.chat.completions.create( model="", messages=[{"role": "user", "content": "Hello!"}] ) print(response.choices[0].message.content) ``` ```typescript TypeScript theme={null} import OpenAI from "openai"; const client = new OpenAI({ apiKey: process.env.COMETAPI_KEY, baseURL: "https://api.cometapi.com/v1", }); const response = await client.chat.completions.create({ model: "", messages: [{ role: "user", content: "Hello!" }], }); console.log(response.choices[0].message.content); ``` ```bash cURL theme={null} curl https://api.cometapi.com/v1/chat/completions \ -H "Authorization: Bearer $COMETAPI_KEY" \ -H "Content-Type: application/json" \ -d '{ "model": "", "messages": [{"role": "user", "content": "Hello!"}] }' ``` Already using the OpenAI SDK? Only `base_url` and `api_key` need to change — your existing application code works without modification. ## Why CometAPI GPT, Claude, Gemini, Nano Banana, Kling, Veo, and hundreds more — accessed with a single API key and a unified endpoint. No monthly fees. Pay only for what you use, with competitive rates across all model categories. Drop-in replacement for the OpenAI SDK. Point to `https://api.cometapi.com/v1` and keep everything else unchanged. Real-time dashboards for request counts, token usage, latency, and per-model cost breakdown. Enterprise-grade security, data privacy, and SLA-backed uptime for production workloads. 1:1 support from real engineers for integration help, model selection, and performance tuning. ## More resources Rate limits, behavioral differences, and key constraints to know before building. Connect CometAPI to Dify, LobeChat, Open WebUI, and 40+ popular AI tools. Error codes, handling strategies, and retry logic for production reliability. # Command reference Source: https://apidoc.cometapi.com/libraries/cli/commands Reference for CometAPI CLI commands, including chat, models, model info, run, balance, account, stats, tokens, logs, tasks, doctor, config, and repl. Use `cometapi -h` or `cometapi -h` to inspect the exact arguments and options for the installed version. ## Commands overview | Command | Description | Auth | | ----------------- | ---------------------------------------------------------------------- | ----------------------- | | `chat [MESSAGE]` | Send a chat message or start the chat REPL | API key | | `models` | List and filter model catalog metadata | API key | | `model info ` | Inspect one model's public metadata | API key | | `run [MODEL]` | Send one request through chat, responses, anthropic, or gemini formats | API key | | `balance` | Show account or current API key balance | API key or access token | | `account` | Show account profile | Access token | | `stats` | Show usage statistics | Access token | | `tokens` | List and search API keys | Access token | | `logs` | Browse usage logs with filters | Access token | | `tasks` | Show async task logs | Access token | | `init` | Run the setup wizard | None | | `doctor` | Run diagnostics | API key | | `config` | Manage local configuration | None | | `repl` | Start an interactive command shell | Depends on command used | Commands marked **Access token** require the `COMETAPI_ACCESS_TOKEN` environment variable or the `access_token` config key. See the [configuration guide](/libraries/cli/configuration) for details. ## Chat Send a single message or start the multi-turn chat REPL. ```bash theme={null} cometapi chat "Explain CometAPI in one sentence." cometapi chat "Summarize this" --model your-model-id --system "Be concise." cometapi chat "Hello" --no-stream cometapi chat "Hello" --json cometapi chat ``` | Option | Short | Description | | ---------------------- | ----- | --------------------------- | | `--model` | `-m` | Model to use | | `--system` | `-s` | System prompt | | `--temperature` | `-t` | Sampling temperature | | `--max-tokens` | | Maximum response tokens | | `--stream/--no-stream` | | Enable or disable streaming | | `--format` | `-f` | Output format | | `--json` | | Output as JSON | ## Models List models from the public catalog by default. Catalog output includes model ID, provider, model type, features, endpoints, pricing, context length, and maximum completion tokens. ```bash theme={null} cometapi models cometapi models --search gpt --limit 10 cometapi models --provider openai --type chat --limit 10 cometapi models --feature image --endpoint responses --json cometapi models --refresh cometapi models --source openai --search gpt ``` | Option | Short | Description | | --------------------------- | ----- | ------------------------------------------------------------ | | `--search` | `-s` | Filter by ID, code, name, description, or provider | | `--provider` | | Filter by provider name or code | | `--type`, `--modality` | | Filter by model type or modality | | `--feature`, `--capability` | | Filter by feature or capability | | `--endpoint` | | Filter by endpoint name, method, or path | | `--limit` | `-l` | Maximum number of results | | `--source` | | Use `catalog` metadata or OpenAI-compatible `openai` listing | | `--refresh` | | Refresh the one-hour catalog cache | | `--no-cache` | | Bypass the catalog cache for this command | | `--format` | `-f` | Output format | | `--json` | | Output as JSON | The catalog cache is stored at `~/.cache/cometapi/models.json`. ## Model info Inspect public metadata for one model. The command resolves the model through the public catalog, then loads detail metadata for the catalog code. ```bash theme={null} cometapi model info your-model-id cometapi model info your-model-id --json cometapi model info your-model-id --refresh ``` | Option | Short | Description | | ------------ | ----- | ----------------------------------------- | | `--refresh` | | Refresh the catalog cache before lookup | | `--no-cache` | | Bypass the catalog cache for this command | | `--format` | `-f` | Output format | | `--json` | | Output raw model detail JSON | Table output includes provider, model type, features, endpoints, pricing, context length, maximum completion tokens, documentation URL, and overview. ## Run Send one request through a selected endpoint format. Use `--input-file` for a JSON body, repeated `-i key=value` values for overrides, and `-p/--prompt` for a prompt shortcut. ```bash theme={null} cometapi run your-model-id -p "Write one sentence about CometAPI." cometapi run your-model-id --endpoint responses -p "Reply with OK only." -i max_output_tokens=32 --json cometapi run your-model-id --endpoint anthropic -p "Reply with OK only." -i max_tokens=32 cometapi run your-model-id --endpoint gemini -p "Reply with OK only." -i generationConfig.maxOutputTokens=32 cometapi run your-model-id --endpoint responses --input-file body.json -i temperature=0.2 --json ``` | Option | Short | Description | | -------------- | ----- | -------------------------------------------------------------- | | `--endpoint` | `-e` | Endpoint format: `chat`, `responses`, `anthropic`, or `gemini` | | `--input-file` | | JSON object request body | | `--input` | `-i` | Request input as `key=value`; repeat for multiple values | | `--prompt` | `-p` | Prompt shortcut | | `--json` | | Output raw JSON response | Endpoint mapping: | Endpoint | Request path | Auth | | ----------- | ---------------------------------- | ------------------------------------------------ | | `chat` | `POST /v1/chat/completions` | Bearer API key | | `responses` | `POST /v1/responses` | Bearer API key | | `anthropic` | `POST /v1/messages` | `x-api-key` API key and Anthropic version header | | `gemini` | Gemini Generate Content model path | `x-goog-api-key` API key | Body merge order is `--input-file`, repeated `-i key=value`, prompt shortcut, then positional `MODEL`. Inline values parse JSON when possible. Dotted keys create nested objects. ## Balance Show your CometAPI account balance or current API key billing view. ```bash theme={null} cometapi balance cometapi balance --source account cometapi balance --source key cometapi balance --json ``` | Option | Short | Description | | ---------- | ----- | ------------------------------- | | `--source` | `-s` | Data source: `account` or `key` | | `--format` | `-f` | Output format | | `--json` | | Output as JSON | ## Account Show your account profile. Requires an access token. ```bash theme={null} cometapi account cometapi account --json ``` ## Stats Show usage statistics. Requires an access token. ```bash theme={null} cometapi stats cometapi stats --json ``` ## Tokens List and search API keys. Requires an access token. ```bash theme={null} cometapi tokens cometapi tokens --search project cometapi tokens --json ``` | Option | Short | Description | | ---------- | ----- | ---------------- | | `--search` | `-s` | Search keyword | | `--page` | `-p` | Page number | | `--limit` | `-l` | Results per page | | `--format` | `-f` | Output format | | `--json` | | Output as JSON | ## Logs Browse usage logs with filters. Requires an access token. ```bash theme={null} cometapi logs cometapi logs --model your-model-id cometapi logs --start 2026-04-01 --end 2026-04-14 cometapi logs --type consume cometapi logs --export > usage.csv cometapi logs --limit 50 --json cometapi logs --request-id 20260617165550885561292gJBlzjtp ``` | Option | Short | Description | | -------------- | ----- | ---------------------------------------------- | | `--model` | `-m` | Filter by model ID | | `--token-name` | `-t` | Filter by API key name | | `--type` | | Log type | | `--search` | `-s` | Search keyword | | `--start` | | Start date | | `--end` | | End date | | `--group` | `-g` | Filter by API key group | | `--request-id` | | Look up one request by `X-Cometapi-Request-Id` | | `--page` | `-p` | Page number | | `--limit` | `-l` | Results per page | | `--export` | | Output server-side CSV to stdout | | `--format` | `-f` | Output format | | `--json` | | Output as JSON | `logs --request-id` performs one indexed lookup against the operator log endpoint and accepts only an exact `request_id` match. The CLI does not scan fallback log pages, because the self-log endpoint does not apply `request_id` filtering. ## Tasks Show async task logs. Requires an access token. ```bash theme={null} cometapi tasks cometapi tasks --platform kling cometapi tasks --status SUCCESS cometapi tasks --json ``` | Option | Short | Description | | ------------ | ----- | --------------------- | | `--platform` | `-p` | Filter by platform | | `--task-id` | | Filter by task ID | | `--status` | `-s` | Filter by status | | `--action` | `-a` | Filter by action type | | `--start` | | Start date | | `--end` | | End date | | `--page` | | Page number | | `--limit` | `-l` | Results per page | | `--format` | `-f` | Output format | | `--json` | | Output as JSON | ## Doctor Run diagnostics to verify configuration and API connectivity. ```bash theme={null} cometapi doctor cometapi doctor --json ``` ## Config Manage CLI configuration stored in `~/.config/cometapi/config.toml`. ```bash theme={null} cometapi config show cometapi config set api_key "$COMETAPI_KEY" cometapi config set default_model your-model-id cometapi config unset api_key cometapi config path ``` See the [configuration guide](/libraries/cli/configuration) for all available keys. ## Init Run the interactive setup wizard: ```bash theme={null} cometapi init ``` ## Repl Start a full interactive command shell: ```bash theme={null} cometapi repl ``` ## Output formats Most data commands support `--json` or `--format`: ```bash theme={null} cometapi models --json cometapi models --format yaml cometapi stats --format csv cometapi account --format markdown ``` | Format | Description | | ---------- | -------------------------- | | `table` | Rich table in the terminal | | `json` | JSON output | | `yaml` | YAML output | | `csv` | Comma-separated values | | `markdown` | Markdown table | # Configuration Source: https://apidoc.cometapi.com/libraries/cli/configuration Configure the CometAPI CLI: config file location, available settings, credential management, environment variables, and security practices. The CometAPI CLI reads settings from a TOML config file, environment variables, and command-line flags. When the same setting is available from multiple sources, the priority order is: **CLI flags > config file > environment variables > defaults** ## Config file Location: `~/.config/cometapi/config.toml` Run the setup wizard to create the config file interactively: ```bash theme={null} cometapi init ``` Or manage individual settings with the `config` subcommand: ```bash theme={null} # View current configuration cometapi config show # Set a value cometapi config set api_key "$COMETAPI_KEY" # Remove a value cometapi config unset api_key # Show the config file path cometapi config path ``` ## Available settings | Config key | Environment variable | Description | | --------------- | ------------------------ | -------------------------------------------------------------------- | | `api_key` | `COMETAPI_KEY` | API key (required for all commands) | | `access_token` | `COMETAPI_ACCESS_TOKEN` | Access token for account-level commands | | `base_url` | `COMETAPI_BASE_URL` | API base URL (default: `https://api.cometapi.com/v1`) | | `default_model` | `COMETAPI_DEFAULT_MODEL` | Default model for `chat` and `run` (fallback: `gpt-5.4`) | | `output_format` | — | Default output format: `table`, `json`, `yaml`, `csv`, or `markdown` | ## Credentials The CLI uses two types of credentials: ### API key Required for all commands. The API key authenticates requests to the CometAPI model endpoints. Create an API key at [CometAPI Console → API Keys](https://www.cometapi.com/console/token). Set it in one of these ways: ```bash Environment variable theme={null} read -rsp "CometAPI API key: " COMETAPI_KEY printf '\n' export COMETAPI_KEY ``` ```bash Config file theme={null} cometapi config set api_key "$COMETAPI_KEY" ``` ```bash Setup wizard theme={null} cometapi init ``` ### Access token Optional. The access token is required for account-level commands: `account`, `stats`, `tokens`, `logs`, and `tasks`. Generate an access token at [CometAPI Console → Personal Settings](https://www.cometapi.com/console/personal). Set it in one of these ways: ```bash Environment variable theme={null} export COMETAPI_ACCESS_TOKEN="your-access-token" ``` ```bash Config file theme={null} cometapi config set access_token your-access-token ``` ```bash Setup wizard theme={null} cometapi init ``` ## Security The CLI applies the following security practices: * API keys and access tokens are never logged or displayed in full. Only the last 4 characters are shown in diagnostics output. * The config file is created with restrictive permissions (`0600`) — readable only by the file owner. * Credentials should never be committed to version control. Add the config file path to your `.gitignore` if applicable. You are responsible for all usage and charges incurred with your API keys. Keep your keys secure and rotate them if you suspect unauthorized access. ## Troubleshooting | Error | Solution | | ----------------------------- | ----------------------------------------------------------------------------------------- | | `API key not configured` | Run `cometapi init` or set the `COMETAPI_KEY` environment variable | | `Connection failed` | Run `cometapi doctor` to diagnose connectivity | | `Access token not configured` | Only needed for `account`/`stats`/`tokens`/`logs`/`tasks`. Run `cometapi init` to add one | # CometAPI CLI Source: https://apidoc.cometapi.com/libraries/cli/overview Install and use the CometAPI command-line interface to chat with models, browse model metadata, run multi-protocol requests, check balance, and inspect usage from the terminal. The [CometAPI CLI](https://pypi.org/project/cometapi-cli/) is the official command-line tool for CometAPI. It helps you chat with models, inspect the model catalog, send one-off requests, check balance, and browse account usage from the terminal. Use the [PyPI package page](https://pypi.org/project/cometapi-cli/) as the public homepage for installation and package metadata. This documentation expands on the same commands without requiring access to the private source repository. The CometAPI CLI is in beta. Command names and options may change while the interface stabilizes. ## Features * Chat with models using streaming output or an interactive REPL * Browse model catalog metadata, including provider, modality, endpoint, capability, context, and pricing fields * Inspect one model with `cometapi model info ` * Send one request through Chat Completions, Responses, Anthropic Messages, or Gemini Generate Content formats with `cometapi run` * Check balance, account profile, usage statistics, API keys, logs, and async task history * Output table, JSON, YAML, CSV, or Markdown data * Store local configuration in `~/.config/cometapi/config.toml` ## Prerequisites * Python 3.10 or later * A [CometAPI API key](https://www.cometapi.com/console/token) ## Install the CLI Install the package from PyPI: ```bash pip theme={null} pip install cometapi-cli ``` ```bash pipx theme={null} pipx install cometapi-cli ``` ```bash uv theme={null} uv tool install cometapi-cli ``` Verify the installed command: ```bash theme={null} cometapi --version cometapi -h ``` ## Start using the CLI Run the setup wizard: ```bash theme={null} cometapi init ``` You can also configure the API key with an environment variable: ```bash theme={null} export COMETAPI_KEY="your-api-key" ``` The optional `COMETAPI_ACCESS_TOKEN` value is only needed for account, stats, tokens, logs, and tasks commands. Send one chat message: ```bash theme={null} cometapi chat "Explain CometAPI in one sentence." ``` Run `cometapi chat` without a message to start the chat REPL. Search the public model catalog: ```bash theme={null} cometapi models --search gpt --limit 10 ``` Filter by catalog metadata: ```bash theme={null} cometapi models --provider openai --type chat --limit 10 cometapi models --feature image --endpoint responses --json ``` Show detail metadata for one model: ```bash theme={null} cometapi model info your-model-id ``` Output the raw detail payload: ```bash theme={null} cometapi model info your-model-id --json ``` Send a one-off request through the default chat endpoint: ```bash theme={null} cometapi run your-model-id -p "Reply with OK only." ``` Select another endpoint format when your request body follows a different provider schema: ```bash theme={null} cometapi run your-model-id --endpoint responses -p "Reply with OK only." --json cometapi run your-model-id --endpoint anthropic -p "Reply with OK only." -i max_tokens=32 cometapi run your-model-id --endpoint gemini -p "Reply with OK only." -i generationConfig.maxOutputTokens=32 ``` ## Get command help Use `-h` on the root command or any subcommand to inspect the options for the installed version: ```bash theme={null} cometapi -h cometapi models -h cometapi model info -h cometapi run -h ``` ## Main commands | Command | Description | | ----------------- | ---------------------------------------------------------------------- | | `chat [MESSAGE]` | Send a chat message or start the chat REPL | | `models` | List and filter model catalog metadata | | `model info ` | Inspect one model's public metadata | | `run [MODEL]` | Send one request through chat, responses, anthropic, or gemini formats | | `balance` | Show account or API key balance | | `account` | Show account profile | | `stats` | Show usage statistics | | `tokens` | List and search API keys | | `logs` | Browse usage logs and export CSV | | `tasks` | Browse async task logs | | `init` | Run the setup wizard | | `doctor` | Run configuration diagnostics | | `config` | Manage local configuration | | `repl` | Start an interactive command shell | ## Links * [PyPI package](https://pypi.org/project/cometapi-cli/) * [Command reference](/libraries/cli/commands) * [Configuration guide](/libraries/cli/configuration) # Configure CometAPI account, billing, and base URL Source: https://apidoc.cometapi.com/overview/important-guidelines Configure CometAPI account basics: claim free credit, top up with Stripe, create API keys, choose model IDs, set the base URL, and review usage logs. # CometAPI getting started guide ## How to claim the \$0.1 USD credit? No special operation required. After registering and logging in, you can see the \$0.1 USD credit in your **Wallet page**. *** ## How to top up? 1. After logging in, enter the amount you wish to add on the **Wallet page**, minimum \$10 USD. 2. Use **stripe** to complete the payment. *** ## Which large language model APIs are available? Current model availability and pricing are listed in the [model page](https://www.cometapi.com/models). Use the [Models page](/overview/models) when you need current model IDs for requests. *** ## How to get an API key? 1. After registering and logging into CometAPI, go to the **"Tokens"** menu on the left, and click **"Add Token"**. 2. Enter a custom name to generate your API key. * This API key can be used for GPT, Claude, Gemini, and all other supported models. *** ## How to switch between models? Change the **`model` parameter** in your code to switch models. Note that you need to enter the complete model ID. For specific usage methods, refer to the [API documentation](/overview/quick-start). *** *** ## Is billing per usage or monthly? 1. **Pay-as-you-go**: Consistent with official pricing, calculated based on Token consumption. You pay only for what you use. * No monthly subscription required, balance never expires, and unused portions are refundable. 2. **Special model billing**: Models like MidJourney, Kling, Luma (image, music, video models) are billed per usage. *** ## Why are there 3 base URLs? Which one should I use? Different development environments or software handle Base URLs differently. Try these 3 addresses: * `https://api.cometapi.com/v1/` * `https://api.cometapi.com/v1/chat/completions/` * `https://api.cometapi.com/` If you encounter a **404 error**, check that your Base URL setting is correct. *** ## Does CometAPI support all Claude model families? Yes. CometAPI supports the full range of Claude models, including: * Sonnet * Haiku * Opus series *** ## Which URL should I use for Anthropic Claude? The Base URL is **the same** for all models: * Including OpenAI, Claude series, Google Gemini, and other models. *** ## How to check how many Tokens were consumed in a call? 1. Go to the **"Logs" page**. 2. Click on a single log entry to expand detailed call information and view the calculation formula and Token consumption: * **Prompt**: Understood as the user input. * **Completion**: Understood as the AI's response. *** ## What do "prompt" and "completion" refer to? * **Prompt**: Refers to the content input by the user. * **Completion**: Refers to the content output by the AI. *** ## What happens if my balance becomes negative? When your balance is very low, if the cost of your last call exceeds your remaining balance, your balance will show as negative. Please top up promptly to continue using the service. # List available CometAPI models Source: https://apidoc.cometapi.com/overview/models api/openapi/overview/get-models.openapi.json GET /api/models Use GET /api/models to fetch the CometAPI model catalog with model IDs, providers, and capabilities for routing chat, image, and video requests. ### Get models list This endpoint retrieves information about all available models. It is a public catalog endpoint and does not require an `Authorization` header. * Method: `GET` * URL: `https://api.cometapi.com/api/models` # Start with CometAPI: create an API key and make your first call Source: https://apidoc.cometapi.com/overview/quick-start Start with CometAPI by creating an API key, setting the base URL, and sending your first curl, Python, or Node.js API request. ## Create an account and API key Create a CometAPI account and API key before you call the API. Open the [CometAPI login page](https://www.cometapi.com/console/login). Continue with Google, continue with GitHub, or enter your email or username. If you do not have an account, complete account creation from this page. CometAPI login page with Google, GitHub, and email sign-in options After you sign in, open the [API key page](https://www.cometapi.com/console/token). You can also select **API Keys** in the dashboard sidebar. Click **Create API Key**, enter a clear name such as `local-test`, and keep **Unlimited Quota** enabled for a first test unless you want to set a spending cap. Click **Create**. CometAPI API keys page with the Create API Key button and create dialog highlighted Click the copy button in the **Key** column. Store the copied key in a server-side environment variable or a local `.env` file. Do not paste a real API key into public repositories, frontend code, screenshots, or support tickets. CometAPI API keys table with the copy button highlighted for a masked API key Request examples read `COMETAPI_KEY` from your environment. ## Store your API key locally For local testing, export your API key as an environment variable: ```bash theme={null} read -rsp "CometAPI API key: " COMETAPI_KEY printf '\n' export COMETAPI_KEY ``` ## Base URL Use this base URL for OpenAI-compatible SDKs and API calls: ```text theme={null} https://api.cometapi.com/v1 ``` ## 30-second switch from OpenAI After you have a CometAPI API key, use this two-setting diff when you switch an OpenAI SDK client to CometAPI: ```diff theme={null} - base_url="https://api.openai.com/v1" - api_key=os.environ["OPENAI_API_KEY"] + base_url="https://api.cometapi.com/v1" + api_key=os.environ["COMETAPI_KEY"] ``` CometAPI uses OpenAI-compatible request formats for common text, image, audio, and video workflows. If your app already uses the OpenAI SDK, start by changing the base URL and API key. ## Make your first call After you set `COMETAPI_KEY` in your environment, replace `your-model-id` with a current model ID from the [Models page](/overview/models). ```bash cURL theme={null} curl https://api.cometapi.com/v1/chat/completions \ -H "Authorization: Bearer $COMETAPI_KEY" \ -H "Content-Type: application/json" \ -d '{ "model": "your-model-id", "messages": [ { "role": "user", "content": "Write a one-sentence bedtime story." } ] }' ``` ```python Python theme={null} import os from openai import OpenAI client = OpenAI( api_key=os.environ["COMETAPI_KEY"], base_url="https://api.cometapi.com/v1", ) completion = client.chat.completions.create( model="your-model-id", messages=[ { "role": "user", "content": "Write a one-sentence bedtime story.", } ], ) print(completion.choices[0].message.content) ``` ```javascript Node.js theme={null} import OpenAI from "openai"; const client = new OpenAI({ apiKey: process.env.COMETAPI_KEY, baseURL: "https://api.cometapi.com/v1", }); const completion = await client.chat.completions.create({ model: "your-model-id", messages: [ { role: "user", content: "Write a one-sentence bedtime story.", }, ], }); console.log(completion.choices[0].message.content); ``` ## Pick a model Choose a model ID from the [Models page](/overview/models), then pass that value in the `model` field. | Goal | Where to start | | -------------------- | ------------------------------------------------------------------------------------------------------------------------------- | | Chat or general text | Use a GPT, Claude, Gemini, DeepSeek, or other chat model with [Chat Completions](/api/text/chat). | | Coding and reasoning | Use a coding or reasoning model with [Responses](/api/text/responses) when the model requires the Responses API. | | Image generation | Use an image model with [Create image](/api/image/openai/images) or a provider-specific image guide. | | Video generation | Use a video model with the video API page that matches the provider workflow, such as [Create video](/api/video/sora-2/create). | ## What is next * For request failures, see [Error Codes & Handling](/errors/error-codes-handling). * For retry guidance, see [how to handle rate limits](/api/text/chat#how-to-handle-rate-limits). * For model-specific usage, start with [Chat Completions](/api/text/chat), [Responses](/api/text/responses), [Create image](/api/image/openai/images), or [Create video](/api/video/sora-2/create). * For billing details, see [About Pricing](/pricing/about-pricing). * To invite team members and manage shared Credits, see [Manage a team with Workspace](/workspace/overview). * For help, see the [Help Center](/support/help-center) or contact [CometAPI support](https://www.cometapi.com/support/). ## FAQ Open the [CometAPI login page](https://www.cometapi.com/console/login), then continue with Google, continue with GitHub, or enter your email or username. If you do not have an account, complete account creation from the same page. Open the [API key page](https://www.cometapi.com/console/token) in the CometAPI dashboard, click **Create API Key**, enter a name, click **Create**, and copy the generated API key. Use `$COMETAPI_KEY` in examples instead of a real API key. Store your API key in a server-side environment variable or a local `.env` file. Do not commit it to public repositories, paste it into frontend code, include it in screenshots, or send it in support tickets. Use `https://api.cometapi.com/v1` for OpenAI-compatible SDKs and endpoints such as `/v1/chat/completions`. Yes. Create an `OpenAI` client, set `api_key` to your CometAPI API key, and set `base_url` to `https://api.cometapi.com/v1`. Change the base URL to `https://api.cometapi.com/v1`, replace the API key with your CometAPI API key, and use a CometAPI model ID from the [Models page](/overview/models). Choose the model ID by use case. Start from the [Models page](/overview/models), then select a chat, coding, image, or video model that matches the API page that you plan to call. CometAPI works with any programming language that can send HTTPS requests. Start with the curl, Python, and Node.js examples on this page, or use an OpenAI-compatible SDK that lets you override the base URL. You can create a CometAPI API key from the dashboard. To check free trial availability, free trial credits, and billing details, see the [CometAPI pricing page](https://www.cometapi.com/pricing/) and [About Pricing](/pricing/about-pricing). # Understand pricing Source: https://apidoc.cometapi.com/pricing/about-pricing Use this guide to understand CometAPI billing units, pricing pages, and account-level pricing notes before calling models. CometAPI adheres to a **transparent, fair** pricing system, divided into the following two situations: *** ## **1. Models with unified official pricing** * **Billing Method**: Billed by **Token**. * **Applicable Models**: Such as OpenAI, Claude series models, etc. * **Billing Rules**: * The consumer price follows an official billing ratio of **0.8:1** compared to the official price, offering users a \*\*20% discount \*\*. * **Volume Discounts**: * For monthly consumption exceeding **3000 USD**, or for enterprise users, please contact customer service for **lower discounts**. *** ## **2. Models without official APIs** * **Billing Method**: Billed by **number of calls**. * **Applicable Models**: Such as MidJourney, Kling, Luma, and other models without official APIs. * **Billing Rules**: * cometAPI implements APIs for these models through technical means, charging per call, with pricing determined by cometAPI. * When using these services, prices also enjoy a **20% discount**. *** # Reference baseline prices for major model APIs Below are links to the baseline prices on the official websites of major model APIs. Click the links for detailed pricing information: * [OpenAI Pricing](https://developers.openai.com/api/docs/models) * [Anthropic Pricing](https://www.anthropic.com/pricing) * [Google Vertex AI Pricing](https://cloud.google.com/vertex-ai/generative-ai/pricing?hl=zh-cn) * [MiniMax Pricing](https://www.minimaxi.com/price) * [StepFun Pricing](https://platform.stepfun.com/docs/zh/guides/pricing/details) * [Lingyiwanwu Pricing](https://platform.lingyiwanwu.com/docs#%E4%BA%A7%E5%93%81%E5%AE%9A%E4%BB%B7) * [Baichuan AI Pricing](https://platform.baichuan-ai.com/prices) * [BigModel Pricing](https://open.bigmodel.cn/pricing) * [DeepSeek Pricing](https://api-docs.deepseek.com/zh-cn/quick_start/pricing/) * [Volcano Engine Pricing](https://www.volcengine.com/docs/82379/1099320) * [Alibaba Cloud Pricing](https://help.aliyun.com/zh/model-studio/getting-started/models?spm=a2c4g.11186623.help-menu-2400256.d_0_2.60e73048zUr7tJ) * [Baidu Wenxin Pricing](https://cloud.baidu.com/doc/WENXINWORKSHOP/s/hlrk4akp7) * [iFLYTEK Spark Pricing](https://xinghuo.xfyun.cn/sparkapi#price) * [Tencent Hunyuan Pricing](https://cloud.tencent.com/product/hunyuan) 🔗 # Query balance and usage Source: https://apidoc.cometapi.com/pricing/balance-query Use the CometAPI CLI or query service API to retrieve account balance, usage, and per-key quota details. CometAPI provides two ways to check account balance and usage: the **CometAPI CLI** and the **query service API** at `query.cometapi.com`. If you use a Workspace, see [Manage a team with CometAPI Workspace](/workspace/overview) to understand shared Organization Credits and billing roles. *** ## CometAPI CLI Check your balance from the terminal with one command. See [CometAPI CLI overview](/libraries/cli/overview) for installation. ```bash theme={null} cometapi balance ``` Add `--source token` for per-key details: ```bash theme={null} cometapi balance --source token ``` See the [commands reference](/libraries/cli/commands) for all available options. *** ## Query service API `GET https://query.cometapi.com/user/quota` Returns account-level balance, cumulative usage, total request count, and per-key quota details. This endpoint uses a separate query service at `query.cometapi.com` and authenticates via the `key` query parameter rather than a Bearer Token. Use a dedicated API key for balance queries. If you want to limit exposure, disable Unlimited Quota and set the smallest positive credit limit allowed by the dashboard. ### Request parameters | Parameter | Type | Required | Description | | ------------ | ------ | -------- | ---------------------------------------------------- | | `key` | string | Yes | Your CometAPI API key | | `start_date` | string | No | Start date for daily breakdown (`YYYY-MM-DD` format) | | `end_date` | string | No | End date for daily breakdown (`YYYY-MM-DD` format) | When `start_date` and `end_date` are provided, the response includes a `daily_quota` field with per-key usage broken down by day. ### Response fields | Field | Type | Description | | ----------------------------------- | ------- | --------------------------------------------------------------------- | | `username` | string | Username | | `total_quota` | number | Current account balance (USD) | | `total_used_quota` | number | Cumulative usage (USD) | | `request_count` | integer | Total request count | | `keys` | array | Per-key quota details | | `keys[].name` | string | API key name | | `keys[].remain_quota` | number | Key remaining quota; `-1` means unlimited | | `keys[].used_quota` | number | Key used quota; `-1` means unlimited | | `daily_quota` | object | Daily usage breakdown (only when `start_date` and `end_date` are set) | | `daily_quota[date]` | array | Per-key usage entries for that date | | `daily_quota[date][].token_name` | string | API key name | | `daily_quota[date][].quota_used` | number | Usage for that key on that date (USD) | | `daily_quota[date][].request_count` | integer | Request count for that key on that date | ### Code examples Query account balance: ```bash curl theme={null} curl "https://query.cometapi.com/user/quota?key=$COMETAPI_KEY" ``` ```python Python theme={null} import os import requests resp = requests.get( "https://query.cometapi.com/user/quota", params={"key": os.environ["COMETAPI_KEY"]} ) data = resp.json() print(f"Balance: ${data['total_quota']:.2f}") print(f"Used: ${data['total_used_quota']:.2f}") print(f"Requests: {data['request_count']}") ``` ```javascript Node.js theme={null} const resp = await fetch( `https://query.cometapi.com/user/quota?key=${process.env.COMETAPI_KEY}` ); const data = await resp.json(); console.log(`Balance: $${data.total_quota.toFixed(2)}`); console.log(`Used: $${data.total_used_quota.toFixed(2)}`); console.log(`Requests: ${data.request_count}`); ``` ### Response example ```json theme={null} { "username": "example_user", "total_quota": 2105.23, "total_used_quota": 21.07, "request_count": 1221, "keys": [ { "name": "my-key", "remain_quota": 8.94, "used_quota": 2.10 } ] } ``` ### Daily breakdown example Query daily usage for a date range: ```bash theme={null} curl "https://query.cometapi.com/user/quota?key=$COMETAPI_KEY&start_date=2026-04-13&end_date=2026-04-14" ``` The response includes the same top-level fields plus `daily_quota`: ```json theme={null} { "username": "example_user", "total_quota": 2105.23, "total_used_quota": 21.07, "request_count": 1221, "daily_quota": { "2026-04-13T00:00:00Z": [ { "token_name": "my-key", "quota_used": 4.27, "request_count": 59 } ], "2026-04-14T00:00:00Z": [ { "token_name": "my-key", "quota_used": 0.57, "request_count": 36 } ] } } ``` # FLUX API quickstart: Generate images with CometAPI Source: https://apidoc.cometapi.com/quickstarts/image/flux-api Create a FLUX.2 Pro image task through CometAPI, poll until it is Ready, and download the resulting PNG. ## What you will build You will submit a `1280x768` PNG task to FLUX.2 Pro, store the returned task `id`, poll `GET /flux/v1/get_result`, and download `result.sample` when the task becomes `Ready`. ## Prerequisites * A CometAPI API key stored in `COMETAPI_KEY` * `curl` and `jq`, Python 3.10+ with `requests`, or Node.js 18+ * Access to `flux-2-pro` on your CometAPI account ## Endpoints and authentication Submit the task: ```text theme={null} POST https://api.cometapi.com/flux/v1/flux-2-pro ``` Poll with the top-level `id` returned by the create response: ```text theme={null} GET https://api.cometapi.com/flux/v1/get_result?id= ``` Authenticate both CometAPI requests with: ```text theme={null} Authorization: Bearer $COMETAPI_KEY ``` ## Code examples ```bash cURL theme={null} set -e CREATE_RESPONSE=$(curl --max-time 60 -fSs https://api.cometapi.com/flux/v1/flux-2-pro \ -H "Authorization: Bearer $COMETAPI_KEY" \ -H "Content-Type: application/json" \ -d '{ "prompt": "A clean editorial photograph of a red ceramic teapot on a pale blue table, a small yellow lemon on the right, soft window light, no text.", "width": 1280, "height": 768, "output_format": "png", "seed": 424242 }') TASK_ID=$(printf "%s" "$CREATE_RESPONSE" | jq -r '.id') for ATTEMPT in $(seq 1 60); do RESULT=$(curl --max-time 30 -fSs "https://api.cometapi.com/flux/v1/get_result?id=$TASK_ID" \ -H "Authorization: Bearer $COMETAPI_KEY") STATUS=$(printf "%s" "$RESULT" | jq -r '.status') echo "status: $STATUS" case "$STATUS" in Ready) IMAGE_URL=$(printf "%s" "$RESULT" | jq -r '.result.sample') curl --max-time 60 -fL "$IMAGE_URL" -o flux-result.png exit 0 ;; Error|Failed|Failure|"Task not found"|"Request Moderated"|"Content Moderated"|failed|failure) echo "FLUX task failed: $STATUS" >&2 exit 1 ;; esac sleep 5 done echo "FLUX task did not finish in time" >&2 exit 1 ``` ```python Python theme={null} import os import time from pathlib import Path import requests headers = {"Authorization": "Bearer " + os.environ["COMETAPI_KEY"]} payload = { "prompt": ( "A clean editorial photograph of a red ceramic teapot on a pale blue " "table, a small yellow lemon on the right, soft window light, no text." ), "width": 1280, "height": 768, "output_format": "png", "seed": 424242, } create_response = requests.post( "https://api.cometapi.com/flux/v1/flux-2-pro", headers={**headers, "Content-Type": "application/json"}, json=payload, timeout=60, ) create_response.raise_for_status() task_id = create_response.json()["id"] failure_statuses = { "Error", "Failed", "Failure", "Task not found", "Request Moderated", "Content Moderated", "failed", "failure", } for _ in range(60): result_response = requests.get( "https://api.cometapi.com/flux/v1/get_result", headers=headers, params={"id": task_id}, timeout=30, ) result_response.raise_for_status() result = result_response.json() status = result.get("status") print(status) if status == "Ready": image_response = requests.get(result["result"]["sample"], timeout=60) image_response.raise_for_status() Path("flux-result.png").write_bytes(image_response.content) break if status in failure_statuses: raise RuntimeError(f"FLUX task failed: {status}") time.sleep(5) else: raise TimeoutError("FLUX task did not finish in time") ``` ```javascript Node.js theme={null} import fs from "node:fs/promises"; const authHeaders = { Authorization: `Bearer ${process.env.COMETAPI_KEY}`, }; const createResponse = await fetch( "https://api.cometapi.com/flux/v1/flux-2-pro", { method: "POST", headers: { ...authHeaders, "Content-Type": "application/json" }, signal: AbortSignal.timeout(60_000), body: JSON.stringify({ prompt: "A clean editorial photograph of a red ceramic teapot on a pale blue table, a small yellow lemon on the right, soft window light, no text.", width: 1280, height: 768, output_format: "png", seed: 424242, }), }, ); if (!createResponse.ok) throw new Error(await createResponse.text()); const { id } = await createResponse.json(); const failureStatuses = new Set([ "Error", "Failed", "Failure", "Task not found", "Request Moderated", "Content Moderated", "failed", "failure", ]); let completed = false; for (let attempt = 0; attempt < 60; attempt += 1) { const resultResponse = await fetch( `https://api.cometapi.com/flux/v1/get_result?id=${encodeURIComponent(id)}`, { headers: authHeaders, signal: AbortSignal.timeout(30_000) }, ); if (!resultResponse.ok) throw new Error(await resultResponse.text()); const result = await resultResponse.json(); console.log(result.status); if (result.status === "Ready") { const imageResponse = await fetch(result.result.sample, { signal: AbortSignal.timeout(60_000), }); if (!imageResponse.ok) throw new Error(await imageResponse.text()); await fs.writeFile( "flux-result.png", Buffer.from(await imageResponse.arrayBuffer()), ); completed = true; break; } if (failureStatuses.has(result.status)) { throw new Error(`FLUX task failed: ${result.status}`); } await new Promise((resolve) => setTimeout(resolve, 5000)); } if (!completed) throw new Error("FLUX task did not finish in time"); ``` ## How the flow works The create endpoint returns a top-level task `id`; it can also return `status: "processing"`. Poll the CometAPI result endpoint with that `id`. `Ready` is the successful terminal state. Treat known error and moderation states as failures, and keep polling other states only until your client timeout. Use `result.sample` only to download the finished image. It is a temporary URL and should not be used as durable application storage. ## Common parameters | Parameter | Use | | -------------------- | ------------------------------------------------------------------------------------------------------------------------------ | | `model` path segment | FLUX.2 model ID in the URL path. This quickstart uses `flux-2-pro`; check [Models](/overview/models) for account availability. | | `prompt` | Required image description or edit instruction. | | `width` / `height` | Requested output dimensions in pixels. | | `output_format` | Format supported by the selected model. This quickstart uses `png`. | | `seed` | Optional seed value. The result can report the used seed; that field alone does not establish repeatable output. | | `input_image` | Public HTTPS reference-image URL for editing. | | `input_image_2` | Second public HTTPS reference-image URL for FLUX.2 Pro; also send `input_image`. | ## Troubleshooting Continue polling within a bounded retry loop. If the client timeout is reached, keep the task ID for later inspection and report the request as timed out rather than successful. Download `result.sample` promptly after the task becomes `Ready`, then place the image in storage that your application controls. Start with the fields in the API reference. Treat additional model-specific controls as unverified until you confirm that the selected CometAPI route preserves and applies them. ## Next steps * Read the [Generate a FLUX image API reference](/api/image/flux/flux-generate-image). * Poll results with [Get a FLUX image result](/api/image/flux/flux-query). * Find available FLUX models in [Models](/overview/models). # Gemini image API quickstart: Generate Nano Banana images with CometAPI Source: https://apidoc.cometapi.com/quickstarts/image/gemini-image-api Generate images with Gemini image models through CometAPI, including Nano Banana model families, and save inlineData output with curl, Python, or Node.js. ## What you will build You will call the Gemini image `generateContent` route through CometAPI, request an image output from Gemini image models including Nano Banana model families, skip intermediate `thought` image parts, and save the final `inlineData` image. ## Prerequisites * A CometAPI API key stored in `COMETAPI_KEY` * Python 3.10+ with `requests`, or Node.js 18+ * A Gemini image model ID. The maintained API reference uses `gemini-3.1-flash-image-preview` as the text-to-image example. ## API key, base URL, authentication Use the Gemini image route through CometAPI: ```text theme={null} https://api.cometapi.com/v1beta/models/gemini-3.1-flash-image-preview:generateContent ``` Authenticate with `x-goog-api-key`: ```text theme={null} x-goog-api-key: $COMETAPI_KEY ``` ## Code examples Use the tabs below for copyable examples in cURL, Python, and Node.js. ```bash cURL theme={null} curl -s -X POST \ "https://api.cometapi.com/v1beta/models/gemini-3.1-flash-image-preview:generateContent" \ -H "x-goog-api-key: $COMETAPI_KEY" \ -H "Content-Type: application/json" \ -d '{ "contents": [ { "parts": [ { "text": "A Monarch butterfly anatomical sketch on textured parchment" } ] } ], "generationConfig": { "responseModalities": ["TEXT", "IMAGE"], "imageConfig": { "aspectRatio": "1:1", "imageSize": "4K" } } }' ``` ```python Python theme={null} import base64 import os import requests response = requests.post( "https://api.cometapi.com/v1beta/models/gemini-3.1-flash-image-preview:generateContent", headers={ "x-goog-api-key": os.environ["COMETAPI_KEY"], "Content-Type": "application/json", }, json={ "contents": [ { "parts": [ { "text": "A Monarch butterfly anatomical sketch on textured parchment" } ] } ], "generationConfig": { "responseModalities": ["TEXT", "IMAGE"], "imageConfig": {"aspectRatio": "1:1", "imageSize": "4K"}, }, }, timeout=120, ) response.raise_for_status() parts = response.json()["candidates"][0]["content"]["parts"] for part in reversed(parts): if part.get("thought") is True: continue inline_data = part.get("inlineData") if inline_data: image_bytes = base64.b64decode(inline_data["data"]) mime_type = inline_data.get("mimeType", "image/png") extension = "jpg" if mime_type == "image/jpeg" else "png" with open(f"nano-banana-result.{extension}", "wb") as file: file.write(image_bytes) break else: raise RuntimeError("No final image part found") ``` ```javascript Node.js theme={null} import fs from "node:fs/promises"; const response = await fetch( "https://api.cometapi.com/v1beta/models/gemini-3.1-flash-image-preview:generateContent", { method: "POST", headers: { "x-goog-api-key": process.env.COMETAPI_KEY, "Content-Type": "application/json", }, body: JSON.stringify({ contents: [ { parts: [ { text: "A Monarch butterfly anatomical sketch on textured parchment", }, ], }, ], generationConfig: { responseModalities: ["TEXT", "IMAGE"], imageConfig: { aspectRatio: "1:1", imageSize: "4K" }, }, }), }, ); if (!response.ok) { throw new Error(await response.text()); } const body = await response.json(); const parts = body.candidates[0].content.parts; const finalImage = [...parts] .reverse() .find((part) => part.thought !== true && part.inlineData); if (!finalImage) { throw new Error("No final image part found"); } const mimeType = finalImage.inlineData.mimeType || "image/png"; const extension = mimeType === "image/jpeg" ? "jpg" : "png"; await fs.writeFile( `nano-banana-result.${extension}`, Buffer.from(finalImage.inlineData.data, "base64"), ); ``` ## Flow explanation Gemini image generation is synchronous on this route. The response uses Gemini native `candidates[].content.parts[]`. Parts can include text, generated images, and intermediate image parts where `thought` is `true`. When saving the result, iterate through image parts, ignore `thought: true`, and save the last remaining `inlineData` image. ## Common parameters | Parameter | Use | | ------------------------------------- | --------------------------------------------------------------------------------------- | | `model` path segment | Gemini image model ID in the URL path. | | `contents` | Prompt and optional input image parts. | | `generationConfig.responseModalities` | Include `IMAGE` when you need image output. | | `generationConfig.imageConfig` | Image options such as aspect ratio and image size when supported by the selected model. | | `tools` | Optional Gemini tools. Add only when the API reference documents the selected workflow. | ## Troubleshooting / FAQ Do not save parts where `thought` is `true`. These are intermediate images, not the final output. Check that `generationConfig.responseModalities` includes `IMAGE`, and that the selected model supports image output. Use `inline_data` request parts as shown in the Gemini image guide, and keep the final-image parsing logic the same. ## Next steps * Read the [Gemini image API reference](/api/image/gemini/gemini-generates-image). * See more examples in [Use Gemini image models](/api/image/gemini/generate-image-guide). * Find available image models in [Models](/overview/models). * Estimate cost with [Estimate request cost before calling a model](/guides/how-to-estimate-cost-before-calling-a-model). # GPT Image API quickstart: Generate images with CometAPI Source: https://apidoc.cometapi.com/quickstarts/image/gpt-image-api Generate a GPT image through CometAPI, decode b64_json, and save the result with curl, Python, or Node.js. ## What you will build You will call `POST /v1/images/generations`, generate one image with a GPT image model, decode the returned `b64_json`, and save it as an image file. ## Prerequisites * A CometAPI API key stored in `COMETAPI_KEY` * Python 3.10+ or Node.js 18+ for file-saving examples * A server-side environment. Do not call image generation from public frontend code with a secret key. ## API key, base URL, authentication Use the OpenAI-compatible image endpoint: ```text theme={null} https://api.cometapi.com/v1/images/generations ``` Authenticate with a Bearer token: ```text theme={null} Authorization: Bearer $COMETAPI_KEY ``` ## Code examples Use the tabs below for copyable examples in cURL, Python, and Node.js. ```bash cURL theme={null} curl https://api.cometapi.com/v1/images/generations \ -H "Authorization: Bearer $COMETAPI_KEY" \ -H "Content-Type: application/json" \ -d '{ "model": "gpt-image-2", "prompt": "A paper boat floating on calm water at sunrise.", "quality": "low", "size": "1024x1024", "output_format": "jpeg" }' ``` ```python Python theme={null} import base64 import os from openai import OpenAI client = OpenAI( api_key=os.environ["COMETAPI_KEY"], base_url="https://api.cometapi.com/v1", ) image = client.images.generate( model="gpt-image-2", prompt="A paper boat floating on calm water at sunrise.", quality="low", size="1024x1024", output_format="jpeg", ) image_base64 = image.data[0].b64_json with open("cometapi-gpt-image.jpeg", "wb") as file: file.write(base64.b64decode(image_base64)) ``` ```javascript Node.js theme={null} import fs from "node:fs/promises"; import OpenAI from "openai"; const client = new OpenAI({ apiKey: process.env.COMETAPI_KEY, baseURL: "https://api.cometapi.com/v1", }); const image = await client.images.generate({ model: "gpt-image-2", prompt: "A paper boat floating on calm water at sunrise.", quality: "low", size: "1024x1024", output_format: "jpeg", }); const imageBase64 = image.data[0].b64_json; await fs.writeFile("cometapi-gpt-image.jpeg", Buffer.from(imageBase64, "base64")); ``` ## Flow explanation GPT image generation returns the completed response in one request. GPT image models return base64 image data in `data[0].b64_json`. Decode that value and write the bytes to a file that matches `output_format`. If you need URL output, check whether the selected model supports URL responses. GPT image models use base64 output in the maintained reference example. ## Common parameters | Parameter | Use | | --------------- | --------------------------------------------------------------------------- | | `model` | GPT image model ID. The reference example uses `gpt-image-2`. | | `prompt` | Text description of the image to generate. | | `size` | Requested output size. Supported values depend on the selected model. | | `quality` | Quality setting for models that support it. | | `output_format` | Encoded image type for GPT image results, such as `jpeg`, `png`, or `webp`. | ## Troubleshooting / FAQ Confirm you decoded `b64_json` as base64 bytes and saved the file extension that matches `output_format`. Image parameters vary by model. Start with the minimal reference example, then add one optional field at a time. Use `b64_json` for GPT image models. URL output is model-specific. ## Next steps * Read the [Create image API reference](/api/image/openai/images). * Find image model IDs in [Models](/overview/models). * Estimate request cost with [Estimate request cost before calling a model](/guides/how-to-estimate-cost-before-calling-a-model). * Handle failures with [Error codes and retry strategy](/guides/error-codes-and-retry-strategy). # Model API quickstarts: Build with CometAPI models Source: https://apidoc.cometapi.com/quickstarts/index Choose a CometAPI model API quickstart for text, image, and video workflows with curl, Python, Node.js, and links to the API reference. Use these quickstarts when you already know the model family or task you want to build. Each page shows a minimal request, a Python example, a Node.js example, the request flow, common parameters, and links back to the API reference. For account setup, API keys, and the first generic call, start with [Create an API key](/overview/quick-start). For reusable platform guidance, use [Core API guides](/guides/use-cometapi-with-openai-sdk). ## Text APIs Use the OpenAI API-compatible Chat Completions route with a CometAPI model ID. Send Anthropic-compatible Messages requests to Claude models through CometAPI. Start with Gemini native `generateContent`, or use OpenAI-compatible Chat Completions for existing SDK apps. ## Image APIs Generate an image, decode `b64_json`, and save the result. Generate images with Gemini image models, including Nano Banana model families. Create a Flux image task, poll for the result, and download it before the URL expires. ## Video APIs Create a Veo video task with multipart form data and poll until completion. Generate a Sora video, poll status, and download completed content. Submit a Kling text-to-video task and track it through polling or callbacks. ## Supporting guides Find available model IDs and route each model to the correct API page. Configure OpenAI-compatible SDK clients with the CometAPI base URL. Plan budget guards before token, image, or video requests. Track async video generation with task IDs, polling, and callbacks. # Claude API quickstart: Send Messages requests with CometAPI Source: https://apidoc.cometapi.com/quickstarts/text/claude-api Call Claude models through CometAPI's Anthropic-compatible Messages API with curl, Python, and Node.js. ## What you will build You will send one request to `POST /v1/messages`, print the Claude response text, and keep the code ready for Anthropic SDK or direct HTTP usage. ## Prerequisites * A CometAPI API key stored in `COMETAPI_KEY` * A Claude model ID from the [Models page](/overview/models) * `curl`, Python 3.10+, or Node.js 18+ ## API key, base URL, authentication Use the Anthropic-compatible Messages endpoint through CometAPI: ```text theme={null} https://api.cometapi.com/v1/messages ``` Authenticate direct HTTP requests with `x-api-key` and the Anthropic API version header: ```text theme={null} x-api-key: $COMETAPI_KEY anthropic-version: 2023-06-01 ``` ## Code examples Use the tabs below for copyable examples in cURL, Python, and Node.js. ```bash cURL theme={null} curl https://api.cometapi.com/v1/messages \ -H "Content-Type: application/json" \ -H "x-api-key: $COMETAPI_KEY" \ -H "anthropic-version: 2023-06-01" \ -d '{ "model": "your-claude-model-id", "max_tokens": 256, "messages": [ { "role": "user", "content": "Reply with one short sentence." } ] }' ``` ```python Python theme={null} import os import anthropic client = anthropic.Anthropic( api_key=os.environ["COMETAPI_KEY"], base_url="https://api.cometapi.com", ) message = client.messages.create( model="your-claude-model-id", max_tokens=256, messages=[ { "role": "user", "content": "Reply with one short sentence.", } ], ) print(message.content[0].text) ``` ```javascript Node.js theme={null} import Anthropic from "@anthropic-ai/sdk"; const client = new Anthropic({ apiKey: process.env.COMETAPI_KEY, baseURL: "https://api.cometapi.com", }); const message = await client.messages.create({ model: "your-claude-model-id", max_tokens: 256, messages: [ { role: "user", content: "Reply with one short sentence.", }, ], }); console.log(message.content[0].text); ``` ## Flow explanation Claude Messages requests are synchronous by default. The API returns a message object in one HTTP response, and your application reads the first text content block. Use this route when you need Claude-specific request shapes such as Anthropic message arrays, extended thinking, prompt caching, or tool use. If your application already uses the official Anthropic SDK, set the SDK base URL to `https://api.cometapi.com` and keep the Messages API request shape. ## Common parameters | Parameter | Use | | ------------ | --------------------------------------------------------------------- | | `model` | A Claude model ID available to your account. | | `max_tokens` | Maximum response token budget for the Messages API response. | | `messages` | Anthropic message array with `user` and `assistant` roles. | | `stream` | Streams incremental message events when set to `true`. | | `thinking` | Enables Claude extended thinking when the selected model supports it. | ## Troubleshooting / FAQ Confirm that `COMETAPI_KEY` is set in the same shell or runtime that sends the request. Do not paste a real key into source files. Confirm that the SDK client sets `base_url` in Python or `baseURL` in Node.js to `https://api.cometapi.com`. Use a Claude model ID available to your account. This quickstart does not hardcode a Claude model because availability changes by account and model family. ## Next steps * Use the [Anthropic Messages API reference](/api/text/anthropic-messages) for full request and response fields. * Check model availability in [Models](/overview/models). * Configure local coding sessions with the [Claude Code integration guide](/integrations/claude-code). * Review retry behavior in [Error codes and retry strategy](/guides/error-codes-and-retry-strategy). # Gemini API quickstart: Use native and OpenAI-compatible requests with CometAPI Source: https://apidoc.cometapi.com/quickstarts/text/gemini-api Call Gemini text models through CometAPI with native generateContent requests or OpenAI-compatible Chat Completions requests. ## What you will build You will send a native Gemini `POST /v1beta/models/\{model\}:generateContent` request, then compare it with the OpenAI-compatible `POST /v1/chat/completions` option for apps that already use Chat Completions request shapes. ## Prerequisites * A CometAPI API key stored in `COMETAPI_KEY` * A Gemini text model ID from the [Models page](/overview/models) * `curl`, Python 3.10+, or Node.js 18+ ## API key, base URL, authentication Use the Gemini native endpoint when you want Gemini request fields: ```text theme={null} https://api.cometapi.com/v1beta/models/{model}:generateContent ``` Use `x-goog-api-key` for direct native Gemini HTTP requests: ```text theme={null} x-goog-api-key: $COMETAPI_KEY ``` Use the OpenAI-compatible base URL only when your application already uses Chat Completions: ```text theme={null} https://api.cometapi.com/v1 ``` ## Native Gemini format Native Gemini requests use `contents`, `parts`, and `generationConfig`. Use this path when you need Gemini-specific fields such as thinking controls, media parts, Google Search grounding, or native streaming operators. ```bash cURL theme={null} curl "https://api.cometapi.com/v1beta/models/your-gemini-model-id:generateContent" \ -H "x-goog-api-key: $COMETAPI_KEY" \ -H "Content-Type: application/json" \ -d '{ "contents": [ { "parts": [ { "text": "Explain why base URL configuration matters." } ] } ], "generationConfig": { "temperature": 0.3 } }' ``` ```python Python theme={null} import os from google import genai client = genai.Client( api_key=os.environ["COMETAPI_KEY"], http_options={"api_version": "v1beta", "base_url": "https://api.cometapi.com"}, ) response = client.models.generate_content( model="your-gemini-model-id", contents="Explain why base URL configuration matters.", config={ "temperature": 0.3, }, ) print(response.text) ``` ```javascript Node.js theme={null} import { GoogleGenAI } from "@google/genai"; const ai = new GoogleGenAI({ apiKey: process.env.COMETAPI_KEY, httpOptions: { baseUrl: "https://api.cometapi.com", apiVersion: "v1beta", }, }); const response = await ai.models.generateContent({ model: "your-gemini-model-id", contents: "Explain why base URL configuration matters.", config: { temperature: 0.3, }, }); console.log(response.text); ``` ## OpenAI-compatible option Use the OpenAI-compatible route when you are migrating an existing OpenAI SDK or Chat Completions app and do not need Gemini native request fields. ```bash cURL theme={null} curl https://api.cometapi.com/v1/chat/completions \ -H "Authorization: Bearer $COMETAPI_KEY" \ -H "Content-Type: application/json" \ -d '{ "model": "your-gemini-model-id", "messages": [ { "role": "user", "content": "Explain why base URL configuration matters." } ] }' ``` ```python Python theme={null} import os from openai import OpenAI client = OpenAI( api_key=os.environ["COMETAPI_KEY"], base_url="https://api.cometapi.com/v1", ) completion = client.chat.completions.create( model="your-gemini-model-id", messages=[ { "role": "user", "content": "Explain why base URL configuration matters.", } ], ) print(completion.choices[0].message.content) ``` ```javascript Node.js theme={null} import OpenAI from "openai"; const client = new OpenAI({ apiKey: process.env.COMETAPI_KEY, baseURL: "https://api.cometapi.com/v1", }); const completion = await client.chat.completions.create({ model: "your-gemini-model-id", messages: [ { role: "user", content: "Explain why base URL configuration matters.", }, ], }); console.log(completion.choices[0].message.content); ``` ## Flow explanation | Path | Endpoint | Request shape | SDK | Use when | | ----------------- | ----------------------------------------------- | -------------------------------------------------- | ------------------------------- | ----------------------------------------------------------------------------------------------------- | | Gemini native | `POST /v1beta/models/\{model\}:generateContent` | `contents`, `parts`, `generationConfig` | Google GenAI SDK or direct HTTP | You need Gemini-specific fields, multimodal parts, thinking controls, grounding, or native streaming. | | OpenAI-compatible | `POST /v1/chat/completions` | `messages`, `temperature`, `max_completion_tokens` | OpenAI SDK or direct HTTP | Your app already uses Chat Completions and only needs a Gemini text model behind that shape. | Do not mix the two request formats. Native Gemini fields such as `contents` and `generationConfig` belong on the `generateContent` route. Chat Completions fields such as `messages` belong on the OpenAI-compatible route. ## Troubleshooting / FAQ Start with native Gemini `generateContent` when you are building a new Gemini workflow. Use the OpenAI-compatible route when an existing app already depends on OpenAI SDK or Chat Completions request shapes. Send `contents`, `parts`, `generationConfig`, and `streamGenerateContent` requests to the Gemini native endpoint. The OpenAI-compatible route expects `messages` and Chat Completions parameters. Confirm that the model ID is available to your account and supports the route you are calling. Use the [Models page](/overview/models) to find current model IDs. For Google GenAI SDK requests, set the base URL to `https://api.cometapi.com`. For OpenAI SDK requests, set `base_url` in Python or `baseURL` in Node.js to `https://api.cometapi.com/v1`. ## Next steps * Use the [Gemini native API reference](/api/text/gemini-generating-content) for full `generateContent` request and response fields. * Read the [Chat Completions API reference](/api/text/chat) for the OpenAI-compatible request shape. * Configure OpenAI SDK clients in [Use CometAPI with OpenAI SDKs](/guides/use-cometapi-with-openai-sdk). * List available models with [List available CometAPI models](/guides/how-to-list-available-models). * Add retry and rate-limit handling with [Error codes and retry strategy](/guides/error-codes-and-retry-strategy). # OpenAI-compatible API quickstart: Send Chat Completions requests with CometAPI Source: https://apidoc.cometapi.com/quickstarts/text/openai-compatible-api Use CometAPI as an OpenAI API-compatible base URL for Chat Completions requests with curl, Python, Node.js, and OpenAI SDKs. This page is a CometAPI OpenAI-compatible API quickstart. It helps you reuse the Chat Completions request shape, OpenAI SDKs, and a CometAPI base URL. It is not an OpenAI account setup guide or an OpenAI-only model page. ## What you will build You will send one text request to CometAPI's OpenAI-compatible `POST /v1/chat/completions` route, print the assistant message, and keep the request shape ready for apps that already use OpenAI SDKs. ## When to use this page Use this quickstart when one of these matches your project: * You already use OpenAI SDKs or Chat Completions request shapes. * You want to switch the base URL to CometAPI. * You want to call a CometAPI model ID through an OpenAI API-compatible route. ## Prerequisites * A CometAPI API key stored in `COMETAPI_KEY` * A text model ID from the [Models page](/overview/models) * `curl`, Python 3.10+, or Node.js 18+ ## API key, base URL, authentication Use the CometAPI base URL with OpenAI-compatible clients: ```text theme={null} https://api.cometapi.com/v1 ``` Authenticate direct HTTP requests with a Bearer token: ```text theme={null} Authorization: Bearer $COMETAPI_KEY ``` ## Code examples Use the tabs below to send the same Chat Completions request with cURL, Python, and Node.js. ```bash cURL theme={null} curl https://api.cometapi.com/v1/chat/completions \ -H "Authorization: Bearer $COMETAPI_KEY" \ -H "Content-Type: application/json" \ -d '{ "model": "your-model-id", "messages": [ { "role": "user", "content": "Write one sentence about CometAPI." } ] }' ``` ```python Python theme={null} import os from openai import OpenAI client = OpenAI( api_key=os.environ["COMETAPI_KEY"], base_url="https://api.cometapi.com/v1", ) completion = client.chat.completions.create( model="your-model-id", messages=[ { "role": "user", "content": "Write one sentence about CometAPI.", } ], ) print(completion.choices[0].message.content) ``` ```javascript Node.js theme={null} import OpenAI from "openai"; const client = new OpenAI({ apiKey: process.env.COMETAPI_KEY, baseURL: "https://api.cometapi.com/v1", }); const completion = await client.chat.completions.create({ model: "your-model-id", messages: [ { role: "user", content: "Write one sentence about CometAPI.", }, ], }); console.log(completion.choices[0].message.content); ``` ## Flow explanation OpenAI-compatible means your application keeps the Chat Completions endpoint, request body, and SDK method names while changing the base URL and model ID to CometAPI values. The route is synchronous by default. The API returns the completed response object in one HTTP response, and your application reads `choices[0].message.content`. For incremental output, set `stream` to `true`. The response becomes Server-Sent Events and ends with `data: [DONE]`. Use streaming for chat interfaces and long responses. Keep the synchronous form for background jobs and simple tests. ## Common parameters | Parameter | Use | | ----------------------- | ---------------------------------------------------------------------------- | | `model` | The CometAPI model ID for a text-capable model. | | `messages` | The conversation array. Start with one `user` message for a minimal request. | | `temperature` | Controls randomness. Lower values make output more deterministic. | | `max_completion_tokens` | Caps generated output for model families that use completion-token budgets. | | `stream` | Streams incremental response chunks when set to `true`. | | `response_format` | Requests JSON output when the selected model supports it. | ## Troubleshooting and FAQ No. This is CometAPI's OpenAI-compatible API route. You use a CometAPI API key, the CometAPI base URL, and a CometAPI model ID. Confirm that `COMETAPI_KEY` is set in the same shell or runtime that sends the request. Do not paste a real key into source files. Use a CometAPI model ID that supports text or chat requests. Check the Models page before retrying. Confirm the client sets `base_url` in Python or `baseURL` in Node.js to `https://api.cometapi.com/v1`. ## Next steps * Read the [Chat Completions API reference](/api/text/chat). * Configure SDK clients in [Use CometAPI with OpenAI SDKs](/guides/use-cometapi-with-openai-sdk). * List available models with [List available CometAPI models](/guides/how-to-list-available-models). * Add retry and rate-limit handling with [Error codes and retry strategy](/guides/error-codes-and-retry-strategy). # Kling API quickstart: Generate videos with CometAPI Source: https://apidoc.cometapi.com/quickstarts/video/kling-api Create a Kling text-to-video task through CometAPI, poll task status, and handle callback-based completion. ## What you will build You will submit a Kling text-to-video task, store the returned task ID, poll the matching Kling task endpoint, and decide when to add `callback_url` for push notifications. ## Prerequisites * A CometAPI API key stored in `COMETAPI_KEY` * Python 3.10+ with `requests`, or Node.js 18+ * A server-side worker for polling or an HTTPS callback endpoint for webhooks ## API key, base URL, authentication Create a Kling text-to-video task with: ```text theme={null} POST https://api.cometapi.com/kling/v1/videos/text2video ``` Poll the task with: ```text theme={null} GET https://api.cometapi.com/kling/v1/videos/text2video/ ``` Authenticate with a Bearer token: ```text theme={null} Authorization: Bearer $COMETAPI_KEY ``` ## Code examples Use the tabs below for copyable examples in cURL, Python, and Node.js. ```bash cURL theme={null} curl https://api.cometapi.com/kling/v1/videos/text2video \ -H "Authorization: Bearer $COMETAPI_KEY" \ -H "Content-Type: application/json" \ -d '{ "prompt": "A small ceramic cup on a wooden table, steam rising in soft morning light", "model_name": "kling-v3", "mode": "std", "duration": "5", "sound": "off" }' curl "https://api.cometapi.com/kling/v1/videos/text2video/" \ -H "Authorization: Bearer $COMETAPI_KEY" ``` ```python Python theme={null} import os import time import requests api_key = os.environ["COMETAPI_KEY"] headers = { "Authorization": f"Bearer {api_key}", "Content-Type": "application/json", } create_response = requests.post( "https://api.cometapi.com/kling/v1/videos/text2video", headers=headers, json={ "prompt": "A small ceramic cup on a wooden table, steam rising in soft morning light", "model_name": "kling-v3", "mode": "std", "duration": "5", "sound": "off", }, timeout=60, ) create_response.raise_for_status() task_id = create_response.json()["data"]["task_id"] for _ in range(60): task_response = requests.get( f"https://api.cometapi.com/kling/v1/videos/text2video/{task_id}", headers={"Authorization": f"Bearer {api_key}"}, timeout=30, ) task_response.raise_for_status() task = task_response.json()["data"] if task["task_status"] in {"succeed", "failed"}: print(task) break time.sleep(5) else: raise TimeoutError("Kling task did not finish in time") ``` ```javascript Node.js theme={null} const createResponse = await fetch( "https://api.cometapi.com/kling/v1/videos/text2video", { method: "POST", headers: { Authorization: `Bearer ${process.env.COMETAPI_KEY}`, "Content-Type": "application/json", }, body: JSON.stringify({ prompt: "A small ceramic cup on a wooden table, steam rising in soft morning light", model_name: "kling-v3", mode: "std", duration: "5", sound: "off", }), }, ); if (!createResponse.ok) { throw new Error(await createResponse.text()); } const created = await createResponse.json(); const taskId = created.data.task_id; for (let attempt = 0; attempt < 60; attempt += 1) { const taskResponse = await fetch( `https://api.cometapi.com/kling/v1/videos/text2video/${taskId}`, { headers: { Authorization: `Bearer ${process.env.COMETAPI_KEY}` } }, ); if (!taskResponse.ok) { throw new Error(await taskResponse.text()); } const task = (await taskResponse.json()).data; if (["succeed", "failed"].includes(task.task_status)) { console.log(task); break; } await new Promise((resolve) => setTimeout(resolve, 5000)); } ``` ## Flow explanation Kling video generation is asynchronous. The create endpoint returns a `data.task_id`. Poll `GET /kling/v1/videos/text2video/` until `data.task_status` reaches `succeed` or `failed`. When the task succeeds, copy the finished asset URL from `data.task_result` into your own storage if you need durable access. Add `callback_url` when you want task status updates pushed to an HTTPS endpoint you control. Keep polling available for reconciliation and missed callback delivery. ## Common parameters | Parameter | Use | | -------------- | ------------------------------------------------------------------------------- | | `prompt` | Text prompt for the video task. | | `model_name` | Kling model ID. The reference example uses `kling-v3`. | | `mode` | Generation mode. Start with `std` before testing higher-cost modes. | | `duration` | Output length. The reference page uses `5` for a first request. | | `sound` | Use `off` for a deterministic no-audio first request on supported model tracks. | | `callback_url` | Optional HTTPS URL for task status callbacks. | ## Troubleshooting / FAQ Kling uses provider-specific JSON fields such as `data.task_id`, `data.task_status`, and `data.task_result`. Do not parse it like the OpenAI-compatible `/v1/videos` routes. Use bounded polling and inspect `data.task_status_msg` when a task fails. Store the task ID for later diagnostics. Use polling as the baseline. Add `callback_url` for push delivery, then reconcile final state with polling. ## Next steps * Read the [Kling text-to-video API reference](/api/video/kling/text-to-video). * Poll with [Get a Kling task](/api/video/kling/individual-queries). * Configure callbacks with [Use Kling callback URLs](/api/video/kling/callback_url). * Find Kling video models in [Models](/overview/models). * Review [Use polling and webhooks for video generation](/guides/webhook-and-polling-for-video-generation). * Estimate task cost with [Estimate request cost before calling a model](/guides/how-to-estimate-cost-before-calling-a-model). # Sora 2 API quickstart: Generate videos with CometAPI Source: https://apidoc.cometapi.com/quickstarts/video/sora-2-api Create a Sora 2 video job with CometAPI, poll status, and download completed video content with curl, Python, or Node.js. ## What you will build You will submit a Sora 2 video job, store the returned video ID, poll until the job completes, and download the finished video content. ## Prerequisites * A CometAPI API key stored in `COMETAPI_KEY` * Python 3.10+ with `requests`, or Node.js 18+ * A server-side worker or job queue for polling ## API key, base URL, authentication Create Sora jobs with: ```text theme={null} POST https://api.cometapi.com/v1/videos ``` Poll status with: ```text theme={null} GET https://api.cometapi.com/v1/videos/ ``` Download completed content with: ```text theme={null} GET https://api.cometapi.com/v1/videos//content ``` Authenticate with a Bearer token: ```text theme={null} Authorization: Bearer $COMETAPI_KEY ``` ## Code examples Use the tabs below for copyable examples in cURL, Python, and Node.js. ```bash cURL theme={null} curl https://api.cometapi.com/v1/videos \ -H "Authorization: Bearer $COMETAPI_KEY" \ -F model=sora-2 \ -F "prompt=A paper boat drifts across a calm pond at sunrise" \ -F seconds=4 \ -F size=1280x720 curl "https://api.cometapi.com/v1/videos/" \ -H "Authorization: Bearer $COMETAPI_KEY" curl "https://api.cometapi.com/v1/videos//content" \ -H "Authorization: Bearer $COMETAPI_KEY" \ --output sora-result.mp4 ``` ```python Python theme={null} import os import time from pathlib import Path import requests api_key = os.environ["COMETAPI_KEY"] headers = {"Authorization": f"Bearer {api_key}"} create_response = requests.post( "https://api.cometapi.com/v1/videos", headers=headers, data={ "model": "sora-2", "prompt": "A paper boat drifts across a calm pond at sunrise", "seconds": "4", "size": "1280x720", }, timeout=60, ) create_response.raise_for_status() video_id = create_response.json()["id"] for _ in range(60): status_response = requests.get( f"https://api.cometapi.com/v1/videos/{video_id}", headers=headers, timeout=30, ) status_response.raise_for_status() status = status_response.json() if status["status"] == "completed": content_response = requests.get( f"https://api.cometapi.com/v1/videos/{video_id}/content", headers=headers, timeout=120, ) content_response.raise_for_status() Path("sora-result.mp4").write_bytes(content_response.content) break if status["status"] == "failed": raise RuntimeError(status) time.sleep(5) else: raise TimeoutError("Sora job did not finish in time") ``` ```javascript Node.js theme={null} import fs from "node:fs/promises"; const form = new FormData(); form.append("model", "sora-2"); form.append("prompt", "A paper boat drifts across a calm pond at sunrise"); form.append("seconds", "4"); form.append("size", "1280x720"); const createResponse = await fetch("https://api.cometapi.com/v1/videos", { method: "POST", headers: { Authorization: `Bearer ${process.env.COMETAPI_KEY}` }, body: form, }); if (!createResponse.ok) { throw new Error(await createResponse.text()); } const { id } = await createResponse.json(); for (let attempt = 0; attempt < 60; attempt += 1) { const statusResponse = await fetch(`https://api.cometapi.com/v1/videos/${id}`, { headers: { Authorization: `Bearer ${process.env.COMETAPI_KEY}` }, }); if (!statusResponse.ok) { throw new Error(await statusResponse.text()); } const status = await statusResponse.json(); if (status.status === "completed") { const contentResponse = await fetch( `https://api.cometapi.com/v1/videos/${id}/content`, { headers: { Authorization: `Bearer ${process.env.COMETAPI_KEY}` } }, ); const videoBuffer = Buffer.from(await contentResponse.arrayBuffer()); await fs.writeFile("sora-result.mp4", videoBuffer); break; } if (status.status === "failed") { throw new Error(JSON.stringify(status)); } await new Promise((resolve) => setTimeout(resolve, 5000)); } ``` ## Flow explanation Sora generation is asynchronous. The create endpoint returns a video ID and an initial status. Poll `GET /v1/videos/` until `status` is `completed` or `failed`. When the job is complete, download the file with `GET /v1/videos//content`. Use exact `WxH` sizes. The Sora API reference documents standard landscape and portrait sizes, with larger Pro sizes for Pro model workflows. ## Common parameters | Parameter | Use | | ----------------- | -------------------------------------------------------------------------- | | `model` | Sora model ID. The reference example uses `sora-2`. | | `prompt` | Text prompt for the video. | | `seconds` | Clip duration. The API reference documents `4`, `8`, `12`, `16`, and `20`. | | `size` | Exact `WxH` output size, such as `1280x720` or `720x1280`. | | `input_reference` | Optional reference image file for first-frame workflows. | ## Troubleshooting / FAQ Use multipart form data. Sora create requests in the reference use form fields, not a JSON body. Download content only after the status endpoint reports `completed`. Store the finished file in your own storage. Use larger Pro sizes only with a Pro model workflow. Start with `1280x720` for a first request. ## Next steps * Read the [Create a Sora 2 video API reference](/api/video/sora-2/create). * Poll with [Retrieve a Sora 2 video](/api/video/sora-2/retrieve). * Download with [Retrieve Sora 2 video content](/api/video/sora-2/retrieve-content). * Find available video models in [Models](/overview/models). * Review [Use polling and webhooks for video generation](/guides/webhook-and-polling-for-video-generation). * Estimate task cost with [Estimate request cost before calling a model](/guides/how-to-estimate-cost-before-calling-a-model). # Veo 3 API quickstart: Generate videos with CometAPI Source: https://apidoc.cometapi.com/quickstarts/video/veo-3-api Create a Veo video task with CometAPI, poll task status, and store completed video output with curl, Python, or Node.js. ## What you will build You will create one Veo video task with multipart form data, store the returned task ID, poll the retrieve endpoint, and save the final asset URL or file in your own system. ## Prerequisites * A CometAPI API key stored in `COMETAPI_KEY` * Python 3.10+ with `requests`, or Node.js 18+ * A server-side job runner for polling ## API key, base URL, authentication Create Veo tasks with: ```text theme={null} POST https://api.cometapi.com/v1/videos ``` Poll Veo task status with: ```text theme={null} GET https://api.cometapi.com/v1/videos/ ``` Authenticate with a Bearer token: ```text theme={null} Authorization: Bearer $COMETAPI_KEY ``` ## Code examples Use the tabs below for copyable examples in cURL, Python, and Node.js. ```bash cURL theme={null} curl https://api.cometapi.com/v1/videos \ -H "Authorization: Bearer $COMETAPI_KEY" \ -F model=veo3.1-fast \ -F "prompt=A paper kite floats above a field." \ -F seconds=4 \ -F size=1280x720 curl "https://api.cometapi.com/v1/videos/" \ -H "Authorization: Bearer $COMETAPI_KEY" ``` ```python Python theme={null} import os import time import requests api_key = os.environ["COMETAPI_KEY"] headers = {"Authorization": f"Bearer {api_key}"} create_response = requests.post( "https://api.cometapi.com/v1/videos", headers=headers, files={ "model": (None, "veo3.1-fast"), "prompt": (None, "A paper kite floats above a field."), "seconds": (None, "4"), "size": (None, "1280x720"), }, timeout=60, ) create_response.raise_for_status() task_id = create_response.json()["id"] for _ in range(60): retrieve_response = requests.get( f"https://api.cometapi.com/v1/videos/{task_id}", headers=headers, timeout=30, ) retrieve_response.raise_for_status() task = retrieve_response.json() if task["status"] in {"completed", "failed", "error"}: print(task) break time.sleep(5) else: raise TimeoutError("Veo task did not finish in time") ``` ```javascript Node.js theme={null} const form = new FormData(); form.append("model", "veo3.1-fast"); form.append("prompt", "A paper kite floats above a field."); form.append("seconds", "4"); form.append("size", "1280x720"); const createResponse = await fetch("https://api.cometapi.com/v1/videos", { method: "POST", headers: { Authorization: `Bearer ${process.env.COMETAPI_KEY}` }, body: form, }); if (!createResponse.ok) { throw new Error(await createResponse.text()); } const { id } = await createResponse.json(); for (let attempt = 0; attempt < 60; attempt += 1) { const retrieveResponse = await fetch(`https://api.cometapi.com/v1/videos/${id}`, { headers: { Authorization: `Bearer ${process.env.COMETAPI_KEY}` }, }); if (!retrieveResponse.ok) { throw new Error(await retrieveResponse.text()); } const task = await retrieveResponse.json(); if (["completed", "failed", "error"].includes(task.status)) { console.log(task); break; } await new Promise((resolve) => setTimeout(resolve, 5000)); } ``` ## Flow explanation Veo video generation is asynchronous. The create endpoint accepts multipart form data and returns a task ID immediately. Poll the retrieve endpoint until the task reaches a terminal status, then persist the final video URL or file details from the completed response. Use short durations and the smallest useful size for first tests. Move completed assets into your own storage when your application needs retention. ## Common parameters | Parameter | Use | | ----------------- | --------------------------------------------------------------- | | `model` | Veo model ID. The API reference example uses `veo3.1-fast`. | | `prompt` | Text prompt for the video job. | | `seconds` | Duration form field. The reference documents `4`, `6`, and `8`. | | `size` | Exact `WxH` size, such as `1280x720`. | | `input_reference` | Optional first-frame image file for image-to-video. | ## Troubleshooting / FAQ Send multipart form data. Do not send Veo create requests as JSON. Use a bounded polling loop, store the task ID, and surface a pending state in your application instead of blocking a web request. Start with a short duration, one task, and the smallest acceptable size. Use account quotas and cost estimation before scaling task count. ## Next steps * Read the [Create a Veo 3 video API reference](/api/video/veo3/create). * Poll with [Retrieve a Veo 3 video](/api/video/veo3/retrieve). * Find Veo video models in [Models](/overview/models). * Review [Use polling and webhooks for video generation](/guides/webhook-and-polling-for-video-generation). * Estimate task cost with [Estimate request cost before calling a model](/guides/how-to-estimate-cost-before-calling-a-model). # Common Misconceptions Source: https://apidoc.cometapi.com/support/common-misconceptions Fix CometAPI token and Key issues: remove token quota limits, set correct Base URL, avoid invalid token errors, and understand concurrency RPM/TPM behavior. ## **1. Why can't I use my token even though I have sufficient balance?** Please check the following two points: * **Token quota limitation**: The token may have a quota limit set, which needs to be removed before continued use. * **Account balance**: Account balance and token quota are independent; tokens need to be set to unlimited quota to function properly. *** ## **2. Why doesn't my Key work? Why is there no response when calling the API?** The most common reason is **incorrect Base URL setting**.\ Solution: * Change the Base URL to: `https://api.cometapi.com`. *** ## **3. What are the interface request limits? Does using multiple Keys together increase concurrency?** * **Individual Keys have no RPM/TPM restrictions**: * **Theoretical concurrency capacity**: * TPM up to 50 million. * RPM up to 30,000. * **Global node load balancing**: Guarantees optimal calling and minimal latency. * **Concurrency upper limit for multiple Keys**: Same as for a single Key, does not stack. * **No group restrictions**: No VIP node grouping restrictions, large concurrent calls welcome ! *** ## **4. Are there concurrency or RPM/TPM limits for a single Key?** No restrictions whatsoever, cometapi supports extremely large concurrency with absolutely no upper limit. *** ## **5. How do I fill in the parameters when creating a new token?** 1. Enter a **token name**. 2. Click the **"Set to unlimited quota"** button. 3. Select the corresponding option in **token grouping**; each group supports production environment level calls. *** ## **6. Why does the API call return "invalid token"?** The most common reason is that the Base URL has not been modified. * Using the default OpenAI official Base URL will cause this issue. * Solution: Change the Base URL to `https://api.cometapi.com/v1`. *** ## **7. How do I analyze images?** 1. Convert local images to **base64 format**. 2. Call the API for analysis. 3. For specific operation methods, refer to the [API documentation](/overview/quick-start). *** # Usage FAQ Source: https://apidoc.cometapi.com/support/confusion-about-use Common CometAPI usage questions about model selection, OpenAI-compatible Claude usage, embeddings, API error codes, and account basics. ## **1. What models should I use for text-to-image generation?** Start from the [Models page](/overview/models) for current availability, then confirm pricing on the [pricing page](https://www.cometapi.com/models/). If you are choosing between providers, focus on the workflow you need first: * text-to-image generation * image editing or variation workflows * provider-specific request formats shown in the API reference For request examples, see [Quick Start](/overview/quick-start) and the corresponding image API docs. *** ## **2. What models should I use for text-to-video generation?** Start from the [Models page](/overview/models) for current video model availability, then confirm pricing on the [pricing page](https://www.cometapi.com/models/). If you need async task handling, polling, or provider-specific request shapes, use [Quick Start](/overview/quick-start) and the relevant video API docs as your reference. *** ## **3. Can I use o-series reasoning models?** Yes. Check the [Models page](/overview/models) for available o-series model identifiers, then call the one you need with the same CometAPI base URL and API key. *** ## **4. Does CometAPI support text embeddings?** Yes. CometAPI supports embedding models and the related OpenAI-compatible workflow. *** ## **5. Meaning of API interface error return codes** Use [Error Codes & Handling](/errors/error-codes-handling) as the canonical reference. That page covers the observed CometAPI behavior for `400`, `401`, and path/base URL failures, plus practical retry guidance for `429` and timeout-class errors. *** ## **6. Does the interface support OpenAI fine-tuning?** **Fine-tuning is not supported.**\ Reason: CometAPI is an aggregated API platform, while fine-tuning requires dedicated account-side ownership and lifecycle management. *** ## **7. Is integration with open-source software supported?** Yes. CometAPI works with many open-source tools and local apps, including **ChatBox**, **Dify**, and **Cline**. For setup details, see the relevant integration guide in the docs. *** ## **8. Does Claude support MCP? Does it support the v1/messages interface?** This interface (`v1/messages`) is not supported. If you need Claude, use the OpenAI-compatible route with a Claude model ID from the [Models page](/overview/models). *** ## **9. Can I use a `.env` file to store API keys?** Yes. Store the key in your `.env` file, and make sure the **Base URL** matches the request format you are using. For OpenAI-compatible examples, the usual Base URL is `https://api.cometapi.com/v1`. *** ## **10. The sample code uses OpenAI, can I change it to use Claude 4.6?** Yes. If the sample uses the OpenAI-compatible SDK or request format, you usually only need to: 1. Keep the same CometAPI base URL and API key. 2. Change the **`model`** value to a Claude 4.6 model ID from the [Models page](/overview/models). 3. Keep the rest of the request shape unchanged unless your chosen model requires provider-specific parameters. You do not need to switch SDKs unless you want to move to Anthropic's native Messages format. *** ## **11. How do I send videos to Gemini models?** CometAPI does not support uploading a video to a separate Gemini Files API path and reusing that uploaded file later. For Gemini `generateContent`, send the video directly in the request: * Use `inlineData` for a local video that you encode as base64. * Use `fileData.fileUri` for a public HTTPS video URL. See [Gemini Generating Content](/api/text/gemini-generating-content) for copyable curl examples. *** ## **12. How do I recover a forgotten password?** 1. On the login page, click the **"Reset Password"** button. 2. Enter the email address used during registration as prompted. 3. Check your email and follow the instructions in the email to complete the password reset. # Help Center Source: https://apidoc.cometapi.com/support/help-center CometAPI Help Center for rate multipliers, pricing updates, concurrency limits, maintenance windows, error handling, and privacy logging policies. # Welcome to CometAPI Access 500+ models using the standard OpenAI interface protocol, with pay-as-you-go billing, transparent details, no hidden costs, and immediate access to all models after recharge. *** # About rate multipliers * **Definition**: Rate multipliers (group multipliers, model multipliers, completion multipliers) are a calculation method in the system. Each model has its independent multiplier, which doesn't directly reflect multiples of official prices. * **Principle**: Theoretically, our multiplier settings are designed to maintain complete consistency with official model pricing. * **Learn More**: Visit [Multiplier Calculation Method](https://www.cometapi.com/console/log). *** # About price adjustments * **GPT Models**: Usually synchronized with official multipliers, unless otherwise stated. * **Other Vendor Models**: Multiplier prices will be adjusted according to market conditions. * Each price adjustment will be publicly announced. For details, follow [Price Adjustment Announcements](https://www.cometapi.com/console/panel). * You can subscribe to multiplier change notifications via email on the [Subscription Page](https://www.cometapi.com/console/profile). *** # About concurrency * **Line descriptions**: * The platform uses large-scale cluster load balancing, supporting high concurrency by default. * For high-concurrency needs or specific model training requirements, use the **training** line and contact customer service to activate relevant model permissions. * **Enterprise-dedicated lines**: Support high concurrency of 30 million TPM by default, with inclusive line support. * **Request Volume Monitoring**: Visit the [Request Log Page](https://www.cometapi.com/console/log) to observe RPM request volume changes. *** # About maintenance * **Multi-channel distribution**: * When a channel fails, the system automatically switches to other channels and retries multiple times. * If a channel crashes, the system will **automatically restart within 5 minutes**. * **Error handling**: * If models return error messages in high-concurrency scenarios, contact customer service for assistance. * **403 Error**: May be triggered by the WAF defense mechanism. Contact customer service to check if the URL is blocked. * **Scheduled Maintenance Time**: * **1-5 AM**: Scheduled tasks, database maintenance, memory release, etc. may cause temporary instability or interruptions. * **Recommendation**: Users with batch concurrent requests should implement reconnection mechanisms and save request data. # Privacy statement * **Recorded Information**: To ensure service quality and network security, we record users' **request IP addresses**, **request frequency**, and **service quota usage**. * **Privacy Commitment**: * Apart from necessary service log information, we do not collect any other personal request data. * We **do not store user request content**, ensuring maximum respect and protection of user privacy. *** # Recharge discounts * **Rules**: The more you recharge, the bigger the discount, with transparent pricing and no hidden fees. * We never use tactics like "ultra-low prices" or "multipliers that are n times the official website". * **Recharge Discounts**: * **Cumulative recharge of 3000+ yuan** or **stable daily consumption of over 100 dollars**, for enterprise customers, contact customer service for permanent recharge or consumption discounts. *** # About abnormal charges * **Handling steps**: 1. Check the **request IP** in the **request logs**. * If it's an unfamiliar IP, your Key may have been leaked. 2. **Solution**: * Disable or delete the leaked API key and create a new one. * **Protect your API key**: Do not share API keys or enter them on unknown websites. * **Open Source Program Considerations**: * If using personally built open-source AI programs, be sure to: * Set up site passwords. * Do not save API keys through environment variables; use form submissions instead. * Modify the **header** and **footer** characteristic information of open-source programs to prevent malicious scanning and unauthorized usage. *** # About recharge credits * **Delay Explanation**: Some network recharges may have a 1-3 minute delay. Please be patient. * **If not credited after 10 minutes**: 1. Contact customer service with payment screenshots and order numbers. 2. We will manually process your order. *** # Contact customer service * Support: [https://www.cometapi.com/support/](https://www.cometapi.com/support/) * Official Website: [https://www.cometapi.com](https://www.cometapi.com) # Interface Stability Source: https://apidoc.cometapi.com/support/interface-stability Understand CometAPI interface limits and stability metrics—RPM, TPM, IPM, VPM, APM—with benchmark performance figures for high-load concurrent calls. # CometAPI parameter descriptions * **RPM (Requests Per Minute)**\ The number of requests that can be processed per minute. * **IPM (Images Per Minute)**\ The number of images that can be processed per minute. * **TPM (Tokens Per Minute)**\ The number of tokens that can be processed per minute. * **VPM (Videos Per Minute)**\ The number of videos that can be processed per minute. * **APM (Audios Per Minute)**\ The number of audios that can be processed per minute. *** # CometAPI performance * **Limit Description**:\ On cometapi, the above six parameters have almost never reached their limits. For SLA and model availability updates, see the [CometAPI model status page](https://status.cometapi.com/status/models). * **Theoretical Performance**: * **TPM**: Up to **50 million**. * **RPM**: Can reach **30,000**. *** # Welcome performance challenges cometapi welcomes all kinds of customers to conduct large-scale concurrent calls and push our performance limits with high-load operations! # Privacy Policy Source: https://apidoc.cometapi.com/support/privacy-policy CometAPI privacy policy covering data protection, what info we collect, third-party logins, security measures, and how we use or share personal data. # CometAPI privacy and data protection policy CometAPI takes user privacy and data protection very seriously. This policy details how we collect, use, store, and protect your personal information. *** ## **1. AI model API interaction data protection** We are committed to protecting your data privacy, especially during your interactions with AI models. To ensure this, we: * **Do not collect user communications with AI models**: We never collect, store, or record any conversation content between you and the AI models, nor will we in the future. * **Do not save user communications with AI models**: Your communication content is not saved to our servers or databases, ensuring your conversations remain completely private and secure. Additionally, storing hundreds of millions of daily requests would be prohibitively expensive and unsustainable for us. Through these measures, we ensure that when using our website, you can enjoy a safe and private interactive environment. *** ## **2. User information** ### **2.1 Automatically collected information** When you visit our website, we may automatically collect the following information: * Your IP address * Browser type and version * Time and date of access * Pages visited and action records * Device type and operating system ### **2.2 Information you provide** We may collect your personal information through the following means: * Username and email address provided during account registration * Contact information submitted through online forms, email, or other methods * Feedback provided when participating in surveys or comments ### **2.3 Third-party login information** #### **2.3.1 GitHub login** With your prior consent, when using Github login, we will collect your Github username and email for account registration and login authorization.\ For more information, please refer to the [Github Privacy Policy](https://github.com/site/privacy). #### **2.3.2 Google login** With your prior consent, when using Google login, we will collect your Google username and email for account registration and login authorization.\ For more information, please refer to the [Google Privacy Policy](https://policies.google.com/privacy). *** ## **3. Use of information** We may use the collected information for the following purposes: * Providing and improving our services * Personalizing your user experience * Processing your requests, orders, or transactions * Sending promotional information, updates, and other relevant communications (you can opt out) * Monitoring and analyzing website usage to enhance website performance and functionality * Protecting our rights, property, or safety *** ## **4. Information sharing** We do not sell or rent your personal information to third parties. *** ## **5. Information security** We implement reasonable technical and organizational measures to protect your personal information from unauthorized access, use, or disclosure. However, no internet transmission or electronic storage method is completely secure, and we cannot guarantee absolute security. *** ## **6. Cookies and tracking technologies** We use cookies and similar technologies to enhance user experience, analyze website traffic, and personalize content. You can disable cookies in your browser settings, but this may affect the website's normal functionality. *** ## **7. Changes to privacy policy** We may update this Privacy and Data Protection Policy from time to time. Changes will be posted on this page with an updated date. Please review regularly to stay informed of the latest policy. *** ## **8. Contact us** If you have any questions or comments about this Privacy and Data Protection Policy, please contact our customer service through the contact information in the footer of this website. Thank you for your attention to and understanding of our Privacy and Data Protection Policy. # Terms of Service Source: https://apidoc.cometapi.com/support/terms-of-service Review CometAPI terms of service covering account security, API usage limits, prohibited activities, billing rules, privacy, and legal compliance. Welcome to CometAPI (hereinafter referred to as "the Service"). Please read the following terms carefully before using the Service. By using this Service, you agree to comply with these terms. If you do not agree to these terms, please do not use the Service. *** ## **1. Service content** CometAPI provides an AI model aggregation platform where users can access various artificial intelligence models, including but not limited to: * Text generation * Text-to-image generation * Image analysis * Audio and video processing For current model availability and service details, please refer to the [CometAPI Models page](/overview/models). *** ## **2. User account** * **Registration Requirements**: You must provide true and accurate information when registering, including but not limited to username, email address, etc. * **Account Security**: You are responsible for protecting your account information and API key. If you discover your account or API key has been compromised, please change it immediately and notify us. * **Usage Restrictions**: It is prohibited to use your account for illegal activities, including but not limited to intellectual property infringement, fraud, etc. *** ## **3. Usage rules** * **API Calls**: You should use the Service correctly according to the API documentation, and must not abuse or call the API beyond reasonable limits. * **Data Storage and Privacy**: * The Service does not collect or store user interactions with AI models. * We may record access logs (such as IP addresses, request frequency, etc.) for service optimization, but this does not involve your private content. * For privacy protection details, please refer to our Privacy Policy. * **Fees and Billing**: * Payment for this service is required at 0.8 of the official pricing. For detailed information, please refer to the pricing guide. * CometAPI may offer usage discounts. For current details, please refer to the pricing guide. *** ## **4. Compliance with legal regulations** * Users must comply with all applicable international laws and the laws and regulations of their country/region when using the Service. * If any disputes, penalties, or legal liabilities arise from users' violations of relevant laws and regulations, CometAPI bears no responsibility. Such responsibilities shall be borne solely by the user. *** ## **5. Prohibited behaviors** Users are prohibited from the following behaviors when using the Service: * Using the Service to attack other systems or platforms. * Violating any applicable laws and regulations. * Using illegal means to obtain, tamper with, or share API keys. * Redistributing or reselling CometAPI services without permission. *** ## **6. Changes to terms** * These terms of service may be updated as needed. Updated terms will be published on this page, and users are advised to check regularly. * If you continue to use the Service after the terms have been updated, you are deemed to have accepted the updated terms. *** ## **7. Contact information** If you have any questions about these terms of service, please contact us through: * **Support**: [https://www.cometapi.com/support/](https://www.cometapi.com/support/) * **Official Website**: [https://www.cometapi.com](https://www.cometapi.com) Thank you for choosing CometAPI. We are committed to serving you! # Manage a team with CometAPI Workspace Source: https://apidoc.cometapi.com/workspace/overview Learn how to invite and remove CometAPI Workspace members, understand Workspace roles, and manage shared Organization Credits. Use a Workspace to manage a team inside a CometAPI Organization. A Workspace defines who can participate in that team. A Workspace does not have a separate Credits balance. Requests from Workspace members use Credits that are available in the Organization context. Workspace roles and Organization roles control different actions. The permission table refers to Workspace roles. Credit administration requires the Organization Owner role. ## Workspace roles Workspace roles control member management. They do not determine who can administer Organization Credits. | Action | Available Workspace roles | | -------------------------- | ------------------------- | | View the member list | Owner, Admin, Member | | Invite members | Owner, Admin | | Cancel pending invitations | Owner, Admin | | Remove another member | Owner, Admin | ## Invite a member To add a person to a Workspace, send an invitation from the Workspace settings. Open [Workspace settings](https://www.cometapi.com/console/workspace/setting), then select the Workspace that you want to manage. In the member list, select **Invite Member**. Enter the person's email address, then send the invitation. The recipient must sign in with the invited email address and accept the invitation within 24 hours. The recipient joins with the Workspace Member role. Workspace Owners and Workspace Admins can cancel a pending invitation from the Workspace settings. ## Remove a member To remove a person from a Workspace, open [Workspace settings](https://www.cometapi.com/console/workspace/setting). In the member list, select the removal action for that member and confirm the change. Removing a member removes every API key record that the member created in this Workspace. If the member does not belong to another Workspace in the Organization, CometAPI also removes the Organization membership. ## Credit administration API requests from Workspace members use the shared Credits that are available in the Organization context. A Workspace does not have a separate Credits balance. Only the Organization Owner can add Credits, configure **Auto Top-Up**, or redeem a redemption code for the Organization. A Workspace Owner or Workspace Admin does not receive these billing permissions unless that person is also the Organization Owner. To manage the shared Credits, open the [Credits page](https://www.cometapi.com/console/credits). ## FAQ A CometAPI Workspace is a team membership area inside an Organization. Workspace roles control who can view and manage the member list. An Organization provides the shared billing context for one or more Workspaces. A Workspace manages its own members and does not have a separate Credits balance. A Workspace Owner or Workspace Admin can invite members, cancel pending invitations, and remove other members. All Workspace roles can view the member list. A Workspace invitation expires 24 hours after it is created. A person who accepts a Workspace invitation joins with the Workspace Member role. No. A Workspace Admin can manage Workspace members, but Credits permissions require the Organization Owner role. Only the Organization Owner can add Credits, configure Auto Top-Up, and redeem a redemption code for the Organization. CometAPI removes every API key record that the member created in that Workspace. If the member has no membership in another Workspace, CometAPI also removes the member from the Organization. ## Related links * [Create an API key](/overview/quick-start) * [Query balance and usage](/pricing/balance-query) * [About pricing](/pricing/about-pricing) * [Help Center](/support/help-center) # Create an API key Source: https://apidoc.cometapi.com/api/api-keys/create-api-key api/openapi/api-keys/create-api-key.openapi.json POST /api/token/ Use CometAPI POST /api/token/ to create an API key for the authenticated account. Use this endpoint to create an API key for automation, internal dashboards, or server-side integrations. Generate a personal access token at [Console → Personal Settings](https://www.cometapi.com/console/personal), then send it as the raw `Authorization` header value. Do not prefix it with `Bearer`. The create response only confirms success. It does not include the new key record or key value. After creation, call [List API keys](./list-api-keys) to read the newest key record. ## Request body | Field | Type | Description | | ---------------------- | -------------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | | `name` | string | User-readable display name for the key. Must be 50 characters or fewer. | | `expired_time` | integer | Unix timestamp in seconds when the key expires. Use `-1` for no expiration. | | `remain_quota` | integer | Starting quota in CometAPI internal quota units. If this reaches `0` and `unlimited_quota` is `false`, model requests with this key are rejected as quota exhausted. | | `unlimited_quota` | boolean | Whether the key bypasses remaining-quota checks. Set `true` only when the key should keep working even if `remain_quota` is `0`. | | `model_limits_enabled` | boolean | Whether to restrict this key to specific models. When `false`, `model_limits` is ignored. | | `model_limits` | string | Comma-separated model IDs allowed by this key when `model_limits_enabled` is `true`. Use model IDs returned by `/v1/models`; use an empty string for no model restriction. | | `allow_ips` | string or null | Optional IP allowlist. Provide one JSON string with entries separated by newline characters (`\n`). Each entry can be a single IPv4 address, single IPv6 address, IPv4 CIDR, or IPv6 CIDR. Use `null` or `""` to disable IP restrictions. | | `group` | string | Optional account group restriction. Use an empty string for no explicit group. Non-empty values must be available to the account, or the API returns `success: false`. | | `cross_group_retry` | boolean | Whether cross-group retry is enabled for automatic group routing. This is only meaningful when the key uses an auto-routed group. | ## Allowlist format To allow multiple IPs or CIDR ranges, send them as one JSON string with `\n` between entries: ```json theme={null} { "allow_ips": "198.51.100.10\n203.0.113.0/24\n2001:db8::/32" } ``` This example allows one IPv4 address, one IPv4 CIDR range, and one IPv6 CIDR range. # Delete an API key Source: https://apidoc.cometapi.com/api/api-keys/delete-api-key api/openapi/api-keys/delete-api-key.openapi.json DELETE /api/token/{id} Use CometAPI DELETE /api/token/{id} to delete one API key by ID for the authenticated account. Use this endpoint to delete an API key by ID. Generate a personal access token at [Console → Personal Settings](https://www.cometapi.com/console/personal), then send it as the raw `Authorization` header value. Do not prefix it with `Bearer`. After deletion, the key can no longer be used for model requests. The response only confirms whether the deletion succeeded. The `id` path parameter is the numeric key ID returned by [List API keys](./list-api-keys). Deleting a key is permanent for that key value; create a new API key if the integration needs credentials again. # Retrieve an API key Source: https://apidoc.cometapi.com/api/api-keys/get-api-key api/openapi/api-keys/get-api-key.openapi.json GET /api/token/{id} Use CometAPI GET /api/token/{id} to retrieve one API key record by ID for the authenticated account. Use this endpoint to retrieve one API key record by ID. Generate a personal access token at [Console → Personal Settings](https://www.cometapi.com/console/personal), then send it as the raw `Authorization` header value. Do not prefix it with `Bearer`. The `id` path parameter is the numeric key ID returned by [List API keys](./list-api-keys). ## API key status | Status | Meaning | | ------ | --------- | | `1` | Enabled | | `2` | Disabled | | `3` | Expired | | `4` | Exhausted | ## Returned fields | Field | Type | Description | | ---------------------- | -------------- | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | | `id` | integer | Numeric API key ID. Use this value with [Update an API key](./update-api-key) and [Delete an API key](./delete-api-key). | | `key` | string | API key value returned by the management API. Treat it as a secret and use it as `Authorization: Bearer $COMETAPI_KEY` for model requests. | | `status` | integer | Operational status. Only `1` means the key is enabled for model requests. | | `name` | string | User-readable display name for the key. | | `created_time` | integer | Unix timestamp in seconds when the key was created. | | `accessed_time` | integer | Unix timestamp in seconds when the key was last used. | | `expired_time` | integer | Unix timestamp in seconds when the key expires. `-1` means no expiration. | | `remain_quota` | integer | Remaining quota in CometAPI internal quota units. | | `used_quota` | integer | Quota already consumed by this key in CometAPI internal quota units. | | `unlimited_quota` | boolean | Whether the key bypasses remaining-quota checks. | | `model_limits_enabled` | boolean | Whether model restrictions are active for this key. | | `model_limits` | string | Comma-separated model IDs allowed by this key when `model_limits_enabled` is `true`. Empty means no configured model list. | | `allow_ips` | string or null | IP allowlist as one newline-separated string. Each entry can be a single IPv4 address, single IPv6 address, IPv4 CIDR, or IPv6 CIDR. `null` or `""` means no IP restriction. | | `group` | string | Account group restriction. Empty means no explicit group restriction. | | `cross_group_retry` | boolean | Whether cross-group retry is enabled for automatic group routing. | # Get current API key Source: https://apidoc.cometapi.com/api/api-keys/get-current-api-key api/openapi/api-keys/get-current-api-key.openapi.json GET /api/usage/token Use CometAPI GET /api/usage/token to retrieve quota, usage, expiration, and model-limit details for the bearer API key. Use this endpoint to inspect the CometAPI API key used by the request. It returns usage and quota fields for the bearer key, not an account-level list of all keys. This endpoint uses a CometAPI API key: `Authorization: Bearer $COMETAPI_KEY`. API key management endpoints use a separate personal access token. ## Returned fields | Field | Type | Description | | ---------------------- | ------- | ----------------------------------------------------------------------------------------------- | | `name` | string | Display name of the API key. | | `total_granted` | integer | Total quota assigned to this key in CometAPI internal quota units. | | `total_used` | integer | Quota consumed by this key in CometAPI internal quota units. | | `total_available` | integer | Remaining quota available to this key in CometAPI internal quota units. | | `unlimited_quota` | boolean | Whether the key bypasses remaining-quota checks. | | `model_limits` | object | Model restrictions for this key, keyed by model ID. Empty when no model limits are configured. | | `model_limits_enabled` | boolean | Whether model restrictions are active for this key. | | `expires_at` | integer | Unix timestamp in seconds when the key expires. `0` means no expiration in this usage response. | # List API keys Source: https://apidoc.cometapi.com/api/api-keys/list-api-keys api/openapi/api-keys/list-api-keys.openapi.json GET /api/token/ Use CometAPI GET /api/token/ to list API keys for the authenticated account with pagination. Use this endpoint to list API keys that belong to the authenticated CometAPI account. The newest keys are returned first. Generate a personal access token at [Console → Personal Settings](https://www.cometapi.com/console/personal), then send it as the raw `Authorization` header value. Do not prefix it with `Bearer`. ## Pagination | Query parameter | Description | | --------------- | ------------------------------------------------------- | | `p` | Page number. Defaults to `1`. | | `page_size` | Items per page. Values above `100` are capped at `100`. | ## API key status | Status | Meaning | | ------ | --------- | | `1` | Enabled | | `2` | Disabled | | `3` | Expired | | `4` | Exhausted | ## Returned fields | Field | Type | Description | | ---------------------- | -------------- | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | | `id` | integer | Numeric API key ID. Use this value with [Get a single API key](./get-api-key), [Update an API key](./update-api-key), and [Delete an API key](./delete-api-key). | | `key` | string | API key value returned by the management API. Treat it as a secret and use it as `Authorization: Bearer $COMETAPI_KEY` for model requests. | | `status` | integer | Operational status. Only `1` means the key is enabled for model requests. | | `name` | string | User-readable display name for the key. | | `created_time` | integer | Unix timestamp in seconds when the key was created. | | `accessed_time` | integer | Unix timestamp in seconds when the key was last used. | | `expired_time` | integer | Unix timestamp in seconds when the key expires. `-1` means no expiration. | | `remain_quota` | integer | Remaining quota in CometAPI internal quota units. | | `used_quota` | integer | Quota already consumed by this key in CometAPI internal quota units. | | `unlimited_quota` | boolean | Whether the key bypasses remaining-quota checks. | | `model_limits_enabled` | boolean | Whether model restrictions are active for this key. | | `model_limits` | string | Comma-separated model IDs allowed by this key when `model_limits_enabled` is `true`. Empty means no configured model list. | | `allow_ips` | string or null | IP allowlist as one newline-separated string. Each entry can be a single IPv4 address, single IPv6 address, IPv4 CIDR, or IPv6 CIDR. `null` or `""` means no IP restriction. | | `group` | string | Account group restriction. Empty means no explicit group restriction. | | `cross_group_retry` | boolean | Whether cross-group retry is enabled for automatic group routing. | # Update an API key Source: https://apidoc.cometapi.com/api/api-keys/update-api-key api/openapi/api-keys/update-api-key.openapi.json PUT /api/token/ Use CometAPI PUT /api/token/ to update an API key by ID with editable fields in the JSON body. Use this endpoint to update an API key's name, status, quota, expiration, model restrictions, IP allowlist, and group settings. Generate a personal access token at [Console → Personal Settings](https://www.cometapi.com/console/personal), then send it as the raw `Authorization` header value. Do not prefix it with `Bearer`. This endpoint uses `PUT /api/token/`, and the `id` belongs in the JSON body. Send the editable fields you want to preserve; omitted numeric, boolean, or string fields can be reset by the update. ## Request body | Field | Type | Description | | ---------------------- | -------------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | | `id` | integer | Required. API key ID returned by [List API keys](./list-api-keys). | | `name` | string | User-readable display name for the key. Must be 50 characters or fewer. | | `status` | integer | Operational status. `1` enables the key for model requests. `2` disables it. `3` marks it expired. `4` marks it quota exhausted. Disabled, expired, or exhausted keys are rejected by model endpoints. | | `expired_time` | integer | Unix timestamp in seconds when the key expires. Use `-1` for no expiration. A past timestamp blocks model requests. | | `remain_quota` | integer | Remaining quota in CometAPI internal quota units. If this reaches `0` and `unlimited_quota` is `false`, model requests with this key are rejected as quota exhausted. | | `unlimited_quota` | boolean | Whether the key bypasses remaining-quota checks. Set `true` only when the key should keep working even if `remain_quota` is `0`. | | `model_limits_enabled` | boolean | Whether to restrict this key to specific models. When `false`, `model_limits` is ignored. | | `model_limits` | string | Comma-separated model IDs allowed by this key when `model_limits_enabled` is `true`. Use model IDs returned by `/v1/models`; use an empty string for no model restriction. | | `allow_ips` | string or null | Optional IP allowlist. Provide one JSON string with entries separated by newline characters (`\n`). Each entry can be a single IPv4 address, single IPv6 address, IPv4 CIDR, or IPv6 CIDR. Use `null` or `""` to disable IP restrictions. | | `group` | string | Optional account group restriction. Use an empty string for no explicit group. Non-empty values must be available to the account, or the API returns `success: false`. | | `cross_group_retry` | boolean | Whether cross-group retry is enabled for automatic group routing. This is only meaningful when the key uses an auto-routed group. | ## Allowlist format To allow multiple IPs or CIDR ranges, send them as one JSON string with `\n` between entries: ```json theme={null} { "allow_ips": "198.51.100.10\n203.0.113.0/24\n2001:db8::/32" } ``` This example allows one IPv4 address, one IPv4 CIDR range, and one IPv6 CIDR range. # Create speech Source: https://apidoc.cometapi.com/api/audio/create-speech api/openapi/audio/post-create-speech.openapi.json POST /v1/audio/speech Use CometAPI POST /v1/audio/speech to convert text into audio with a selected text-to-speech model and output format. Use this endpoint to turn text into an audio file through the OpenAI-compatible audio API. It fits narration, short voice prompts, read-aloud features, and other workflows where your app already has text and needs speech output. ## First request Start with three fields: `model`, `input`, and `voice`. Keep the first request short so you can verify authentication, audio format, and file handling before you tune speed or output format. ## Read the response The response is binary audio, not JSON. In SDK examples, write the response to a file such as `output.mp3`. In direct HTTP clients, save the response body and set the file extension to match the requested `response_format`. ## Next steps * Use [Create Transcription](/api/audio/create-transcription) when you need to turn speech back into text. * Use [Create Translation](/api/audio/create-translation) when you need English text from non-English audio. # Create transcription Source: https://apidoc.cometapi.com/api/audio/create-transcription api/openapi/audio/post-create-transcription.openapi.json POST /v1/audio/transcriptions Use CometAPI POST /v1/audio/transcriptions to transcribe audio into text with a selected transcription model and response format. Use this endpoint to transcribe audio into text in the source language. It fits meeting notes, voice messages, media indexing, captions, and support workflows that need searchable text. ## First request Send a supported audio file with `model` and `file`. Keep the first file short while you validate upload handling, authentication, and response parsing. ## Read the response The default response includes the transcribed `text`. If you request another response format, make sure your client parses that format instead of assuming the default JSON shape. ## Next steps * Use [Create Speech](/api/audio/create-speech) when you need text-to-speech output. * Use [Create Translation](/api/audio/create-translation) when the target output should be English. # Create translation Source: https://apidoc.cometapi.com/api/audio/create-translation api/openapi/audio/post-create-translation.openapi.json POST /v1/audio/translations Use CometAPI POST /v1/audio/translations to translate spoken audio into English text with a selected translation model and response format. Use this endpoint to translate spoken audio into English text. It fits multilingual support queues, media review, and workflows that need one English transcript from audio in another language. ## First request Send a supported audio file with `model` and `file`. Use a short sample first so you can verify upload handling, language detection, and output parsing. ## Read the response The default response includes translated English `text`. If you request a different response format, parse the response according to that format. ## Next steps * Use [Create Transcription](/api/audio/create-transcription) when you need text in the original language. * Use [Create Speech](/api/audio/create-speech) when you need to generate audio from text. # Audio APIs Source: https://apidoc.cometapi.com/api/audio/index Choose CometAPI audio routes for text-to-speech, transcription, and audio translation workflows. Use CometAPI audio model docs by choosing whether your app needs speech output, transcription, or translation. Audio endpoints use the same CometAPI API key pattern as other OpenAI-compatible endpoints. ## Choose an audio API Convert text to speech. Transcribe audio to text. Translate audio to English text. ## Create speech Use an audio-capable model ID from the [Models page](/overview/models) or the [model directory](https://www.cometapi.com/models/). The examples below call the speech endpoint. These examples use the placeholder `your-audio-model-id`. Replace it with an available audio model ID from the [Models page](/overview/models) or [model directory](https://www.cometapi.com/models/) before you run the request. Open [Create speech](/api/audio/create-speech) to use the playground and endpoint schema. ```python Python theme={null} import os import requests response = requests.post( "https://api.cometapi.com/v1/audio/speech", headers={ "Authorization": "Bearer " + os.environ["COMETAPI_KEY"], "Content-Type": "application/json", }, json={ "model": "your-audio-model-id", "input": "Welcome to CometAPI.", "voice": "alloy", "response_format": "mp3", }, timeout=60, ) response.raise_for_status() with open("speech.mp3", "wb") as audio_file: audio_file.write(response.content) ``` ```javascript Node.js theme={null} import { writeFile } from "node:fs/promises"; const response = await fetch("https://api.cometapi.com/v1/audio/speech", { method: "POST", headers: { Authorization: `Bearer ${process.env.COMETAPI_KEY}`, "Content-Type": "application/json", }, body: JSON.stringify({ model: "your-audio-model-id", input: "Welcome to CometAPI.", voice: "alloy", response_format: "mp3", }), }); if (!response.ok) { throw new Error(await response.text()); } const audio = Buffer.from(await response.arrayBuffer()); await writeFile("speech.mp3", audio); ``` ```bash cURL theme={null} curl https://api.cometapi.com/v1/audio/speech \ -H "Authorization: Bearer $COMETAPI_KEY" \ -H "Content-Type: application/json" \ -d '{ "model": "your-audio-model-id", "input": "Welcome to CometAPI.", "voice": "alloy", "response_format": "mp3" }' \ --output speech.mp3 ``` ## Response example A successful speech response is binary audio. The HTTP response can look like this: ```text theme={null} HTTP/1.1 200 OK Content-Type: audio/mpeg speech.mp3 ``` ## Example model records This example model catalog response shows the `/api/models` envelope and one audio model record shape. It is not a complete model list. ```bash cURL theme={null} curl https://api.cometapi.com/api/models ``` ```json theme={null} { "success": true, "page": 1, "page_size": 20, "total": 302, "data": [ { "created": 0, "id": "your-audio-model-id", "code": "your-audio-model-id", "provider": "ExampleProvider", "provider_code": "example", "name": "Example audio model", "model_type": "audio", "features": [ "text-to-speech" ], "endpoints": [ "openai" ], "pricing": { "currency": "USD / M Tokens", "input": 12, "output": 12, "per_request": null, "per_second": null } } ] } ``` ## Common errors Use the formats documented on the endpoint page. Compress the audio file or split the job into smaller files. Confirm that the file contains speech and that the field name matches the docs. Use `https://api.cometapi.com/v1`. ## Error codes and retry strategy Do not retry until the text, file, model ID, voice, or format is fixed. Do not retry until the API key is present and valid. Check the base URL, path, and model ID before retrying. Reduce upload size before retrying. Retry with exponential backoff and reduce concurrency. Retry with backoff for transient provider or service errors. For implementation patterns, see [Error codes and retry strategy](/guides/error-codes-and-retry-strategy) and [Rate limits and concurrency](/guides/rate-limits-and-concurrency). ## Pricing and model directory Read how CometAPI exposes model IDs in the docs. Browse model availability and capabilities. Check pricing before you call a model. # Create a moderation Source: https://apidoc.cometapi.com/api/content-moderation/create-moderation api/openapi/content-moderation/create-moderation.openapi.json POST /v1/moderations Use CometAPI POST /v1/moderations to check text or multimodal input with an OpenAI-compatible moderation request. Use this endpoint to check user-generated content before you send it to a model endpoint. Send an OpenAI-compatible moderation request with a `model` and an `input` value. Use a CometAPI API key in the bearer header: `Authorization: Bearer $COMETAPI_KEY`. ## Request body | Field | Type | Required | Description | | ------- | --------------- | -------: | ----------------------------------------------------------------------------------------------------------------------------------------------------------------- | | `input` | string or array | Yes | The content to check. Use a string for one text input, an array of strings for batch text checks, or OpenAI-style multimodal parts such as text plus `image_url`. | | `model` | string | Yes | Moderation model ID. Use `omni-moderation-latest` for text and image moderation unless you have a specific moderation model requirement. | For multimodal moderation, send OpenAI-style multimodal input with a model that supports it, such as `omni-moderation-latest`. Public image URLs must be downloadable by CometAPI servers. For a copyable image test, use a base64 data URL. ## Request examples Send a single text string when you only need to classify one text input: ```bash theme={null} curl https://api.cometapi.com/v1/moderations \ -H "Content-Type: application/json" \ -H "Authorization: Bearer $COMETAPI_KEY" \ -d '{ "model": "omni-moderation-latest", "input": "I want to bake cookies for my family." }' ``` Send an array of strings when you want to check multiple text inputs in one request: ```bash theme={null} curl https://api.cometapi.com/v1/moderations \ -H "Content-Type: application/json" \ -H "Authorization: Bearer $COMETAPI_KEY" \ -d '{ "model": "omni-moderation-latest", "input": [ "I want to bake cookies.", "I want to kill someone." ] }' ``` Send text plus an image URL when your moderation input includes an image that CometAPI can download: ```bash theme={null} curl https://api.cometapi.com/v1/moderations \ -H "Content-Type: application/json" \ -H "Authorization: Bearer $COMETAPI_KEY" \ -d '{ "model": "omni-moderation-latest", "input": [ { "type": "text", "text": "...text to classify goes here..." }, { "type": "image_url", "image_url": { "url": "https://www.gstatic.com/webp/gallery/1.png" } } ] }' ``` Use a base64 data URL when you need a self-contained image request: ```bash theme={null} curl https://api.cometapi.com/v1/moderations \ -H "Content-Type: application/json" \ -H "Authorization: Bearer $COMETAPI_KEY" \ -d '{ "model": "omni-moderation-latest", "input": [ { "type": "text", "text": "...text to classify goes here..." }, { "type": "image_url", "image_url": { "url": "data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAAAAAA6fptVAAAADElEQVR4nGP4//8/AAX+Av4N70a4AAAAAElFTkSuQmCC" } } ] }' ``` ## Response shape The response includes `id`, `model`, `results`, and `usage`. Each item in `results` reports whether the matching input was flagged, category booleans, category scores, and input types applied to each category. For a batch text request, `results` contains one item per input string. Use `usage` for billing and monitoring fields. # Embeddings API Source: https://apidoc.cometapi.com/api/embeddings/index Use CometAPI embeddings routes to create vectors for semantic search, clustering, recommendations, and retrieval workflows. Use CometAPI embeddings when your app needs vectors for semantic search, clustering, recommendations, or retrieval. Send text to `/v1/embeddings`, store the returned vector, and search it with your vector database. ## Create an embedding Use an embedding-capable model ID from the [Models page](/overview/models) or the [model directory](https://www.cometapi.com/models/). The examples below call the OpenAI-compatible Embeddings API. These examples use the placeholder `your-embedding-model-id`. Replace it with an available embedding model ID from the [Models page](/overview/models) or [model directory](https://www.cometapi.com/models/) before you run the request. Open [Create embeddings](/api/text/embeddings) to use the playground and endpoint schema. ```python Python theme={null} import os import requests response = requests.post( "https://api.cometapi.com/v1/embeddings", headers={ "Authorization": "Bearer " + os.environ["COMETAPI_KEY"], "Content-Type": "application/json", }, json={ "model": "your-embedding-model-id", "input": "CometAPI lets developers use many model providers.", }, timeout=30, ) response.raise_for_status() result = response.json() print(len(result["data"][0]["embedding"])) ``` ```javascript Node.js theme={null} const response = await fetch("https://api.cometapi.com/v1/embeddings", { method: "POST", headers: { Authorization: `Bearer ${process.env.COMETAPI_KEY}`, "Content-Type": "application/json", }, body: JSON.stringify({ model: "your-embedding-model-id", input: "CometAPI lets developers use many model providers.", }), }); if (!response.ok) { throw new Error(await response.text()); } const result = await response.json(); console.log(result.data[0].embedding.length); ``` ```bash cURL theme={null} curl https://api.cometapi.com/v1/embeddings \ -H "Authorization: Bearer $COMETAPI_KEY" \ -H "Content-Type: application/json" \ -d '{ "model": "your-embedding-model-id", "input": "CometAPI lets developers use many model providers." }' ``` ## Response example A successful response can look like this. The response includes one vector for each input item; the vector below is shortened for readability: ```json theme={null} { "object": "list", "data": [ { "object": "embedding", "index": 0, "embedding": [ -0.0021, -0.0491, 0.0209 ] } ], "model": "your-embedding-model-id", "usage": { "prompt_tokens": 10, "total_tokens": 10 } } ``` ## Batch input Send an array of strings when you want several vectors from one request: ```bash cURL theme={null} curl https://api.cometapi.com/v1/embeddings \ -H "Authorization: Bearer $COMETAPI_KEY" \ -H "Content-Type: application/json" \ -d '{ "model": "your-embedding-model-id", "input": [ "Create an API key", "Change the base URL", "Retry after a rate limit" ] }' ``` ## Example model records This example model catalog response shows the `/api/models` envelope and one OpenAI-compatible embedding model record shape. Some embedding records use an empty `model_type`; choose an embedding model by ID and endpoint support instead of relying on that field alone. ```bash cURL theme={null} curl https://api.cometapi.com/api/models ``` ```json theme={null} { "success": true, "page": 1, "page_size": 20, "total": 302, "data": [ { "created": 1757904564, "id": "your-embedding-model-id", "code": "your-embedding-model-id", "provider": "ExampleProvider", "provider_code": "example", "name": "Example embedding model", "model_type": "embedding", "features": [ "text-embedding" ], "endpoints": [ "openai" ], "pricing": { "currency": "USD / M Tokens", "input": 0.1, "output": null, "per_request": null, "per_second": null } } ] } ``` ## Common errors Split long documents into chunks before embedding. Choose an embedding-capable model from the model directory. Keep the same model and dimensions for one vector index. Send `Authorization: Bearer $COMETAPI_KEY`. ## Error codes and retry strategy Do not retry until the input, model ID, or dimensions setting is fixed. Do not retry until the API key is present and valid. Check the base URL, path, and model ID before retrying. Retry with exponential backoff and reduce batch size or concurrency. Retry with backoff for transient provider or service errors. For implementation patterns, see [Error codes and retry strategy](/guides/error-codes-and-retry-strategy) and [Rate limits and concurrency](/guides/rate-limits-and-concurrency). ## Pricing and model directory Read how CometAPI exposes model IDs in the docs. Browse model availability and capabilities. Check pricing before you call a model. # Create embeddings Source: https://apidoc.cometapi.com/api/text/embeddings api/openapi/text/post-embeddings.openapi.json POST /v1/embeddings Use CometAPI POST /v1/embeddings to create vector embeddings for text input with a selected embedding model. CometAPI supports embedding models from multiple providers through a single endpoint. Pass one or more text strings and receive numerical vectors for semantic search, clustering, classification, or retrieval-augmented generation (RAG). See the [model list](/overview/models) for available embedding models and pricing. The `text-embedding-3-*` models support the `dimensions` parameter, which shortens the embedding vector without significant accuracy loss. This can reduce storage costs while retaining most semantic information. To embed multiple texts in a single request, pass an array of strings to the `input` parameter. Batch input is significantly more efficient than making individual requests. *** # Create a Kling avatar video Source: https://apidoc.cometapi.com/api/video/kling/avatar api/openapi/video/kling/post-avatar.openapi.json POST /kling/v1/videos/avatar/image2video Generate avatar-driven videos from images using the Kling Avatar API in CometAPI. Use POST /kling/v1/videos/avatar/image2video for fast image-to-video avatars. Use this endpoint to create talking-avatar clips from one source image plus one audio source. ## Before you call it * Provide one avatar `image` as a public URL or raw base64 string * Use an avatar image that meets Kling pixel requirements; tiny thumbnails are rejected by the generation task * Send exactly one of `audio_id` or `sound_file` * Keep the first request simple: one face image, one audio clip, and a short optional prompt * Include `task_id` when the referenced audio belongs to a prior task that must be linked * Start with `mode: std` unless you specifically need the higher-quality path ## Audio source rules * `audio_id` is the easiest path when you already generated speech through the Kling TTS route * `sound_file` works when you already have your own MP3, WAV, M4A, or AAC asset * Avatar audio is documented as 2 to 60 seconds long ## Task flow Submit the image and one audio source, then save the returned task id. Continue with [Get a Kling task](./individual-queries) until the task reaches a terminal state. Copy the final asset into your own storage if you need retention beyond the provider delivery URL. For the complete parameter reference, see the [official Kling Avatar documentation](https://kling.ai/document-api/apiReference/model/avatar). # Use Kling callback URLs Source: https://apidoc.cometapi.com/api/video/kling/callback_url Configure Kling callback_url in CometAPI to receive async video/image task status updates and results payloads (submitted to succeed/failed). Use `callback_url` on Kling async tasks when you want push delivery instead of pure polling. ## Where to use it * Text-to-video and image-to-video tasks * Avatar and video-effects tasks * Other Kling async routes that expose an optional `callback_url` field ## Delivery behavior * Kling posts to your callback endpoint whenever task status changes * Common statuses are `submitted`, `processing`, `succeed`, and `failed` * The payload can include `task_result.images` or `task_result.videos` depending on the task type * Keep manual polling available for reconciliation, retries, or missed webhook handling ## Integration checklist * Use an HTTPS callback endpoint you control * Accept repeated status updates for the same task id * Treat webhook delivery as asynchronous and eventually consistent * Persist the final asset URLs quickly if your workflow needs durable storage ```jsonc theme={null} { "task_id": "string", "task_status": "string", "task_status_msg": "string", "created_at": 1722769557708, "updated_at": 1722769557708, "task_result": { "images": [ { "index": 0, "url": "https://example.com/generated-image.png" } ], "videos": [ { "id": "string", "url": "https://example.com/generated-video.mp4", "duration": "5" } ] } } ``` # Create a Kling advanced lip-sync task Source: https://apidoc.cometapi.com/api/video/kling/counterpart-creating-tasks api/openapi/video/kling/post-counterpart-creating-tasks.openapi.json POST /kling/v1/videos/advanced-lip-sync Create advanced lip-sync video tasks via CometAPI Kling POST /kling/v1/videos/advanced-lip-sync, submit audio and counterpart settings to generate synced results. Use this endpoint to create an advanced lip-sync task after you already identified faces in the source video. ## Before you call it * Start with [Lip-Sync](./lip-sync) to get the `session_id` and available `face_id` values * Build one or more `face_choose` entries that map each face to an audio segment * Use `audio_id` for audio produced by a prior task, or `sound_file` for a hosted audio file * Send timing fields in milliseconds. For example, `sound_start_time: "0"` and `sound_end_time: "2000"` select the first 2 seconds. * Make sure the clipped audio segment is at least 2000 ms and does not exceed the source audio duration * Set `callback_url` or `external_task_id` only when you need webhook delivery or your own tracking id ## Task flow Run [Lip-Sync](./lip-sync) on the source video and keep the returned `session_id` plus the target `face_id` values. Submit `session_id` and the `face_choose` array through this endpoint. Save the returned task id for status checks and final result retrieval. For the complete parameter reference, see the [official Kling documentation](https://kling.ai/document-api/apiReference/model/lipSync). # Recognize images with Kling Source: https://apidoc.cometapi.com/api/video/kling/image-recognize api/openapi/video/kling/post-image-recognize.openapi.json POST /kling/v1/videos/image-recognize Use CometAPI POST /kling/v1/videos/image-recognize to run Kling Image Recognize on images and return recognition results for video generation workflows. Use this endpoint to run Kling's image-recognition checks before you decide which downstream workflow to use. ## What it returns * The route is synchronous and returns recognition flags directly * Current results indicate whether the image contains regions such as `head_seg`, `face_seg`, `cloth_seg`, and `object_seg` * Use these flags to decide whether a source image is suitable for avatar, try-on, or other asset-driven workflows For the complete parameter reference, see the [official Kling documentation](https://app.klingai.com/global/dev/document-api/apiReference/model/imageRecognize). # Create a Kling image-to-video task Source: https://apidoc.cometapi.com/api/video/kling/image-to-video api/openapi/video/kling/post-image-to-video.openapi.json POST /kling/v1/videos/image2video Convert a single image into a Kling video via CometAPI POST /kling/v1/videos/image2video, with async task creation and progress tracking by task ID. Use this endpoint to animate one source image into a Kling video. ## Before you call it * Provide one public image URL or one base64 image string * Use an image that meets Kling pixel requirements; tiny thumbnails are rejected by the generation task * Start with the default `kling-v2-6` example, then choose another `model_name` from the OpenAPI enum when you need a different model track * Keep the first request simple: one input image, one prompt, no tail frame, no motion masks * Use `dynamic_masks` as an array of mask-and-trajectory objects when you need controlled local motion * Use `sound: off` for a deterministic no-audio first request on model tracks that support generated sound ## Model naming Use ordinary Kling video model IDs on this endpoint. Keep Omni model IDs for [Omni Video](./omni-video). ## Task flow Create the task and store the returned Kling `task_id`. Continue with [Get a Kling task](./individual-queries) to follow task status until output is ready. Persist the finished asset if you need retention beyond the provider delivery URL. For the full parameter reference, see the [official Kling document](https://kling.ai/document-api/apiReference/model/imageToVideo). # Get a Kling task Source: https://apidoc.cometapi.com/api/video/kling/individual-queries api/openapi/video/kling/get-individual-queries.openapi.json GET /kling/v1/{action}/{action2}/{task_id} Query a Kling video generation task by task_id and return its status, progress, and result metadata for polling. Use this endpoint family after you create a Kling task. It is the common polling step for Kling async media jobs. A query can return the task object directly or inside the standard `data` envelope. Normalize each response with `task = payload.data ?? payload` before reading task fields. ## What to check first * `task.task_status`; Motion Control tasks use `submitted`, `processing`, `succeed`, or `failed` * `task.task_result.videos[0].url` when a video task succeeds * `task.task_status_msg` or other returned detail fields when a task stops early * `code`, `message`, and `request_id` when the response uses the standard envelope ## Polling pattern Start with the Kling creation page for your workflow, such as [Text to Video](./text-to-video), [Image to Video](./image-to-video), or [Motion Control](./motion-control). Normalize the response shape, then keep querying with the returned task id until it reaches a terminal state. For Motion Control, the terminal states are `succeed` and `failed`. Use the finished output directly, or move into the next applicable action page if your workflow supports chained operations. ## Common path pairs | Workflow | Query path | | ----------------- | ----------------------------------------------- | | Text to video | `/kling/v1/videos/text2video/{task_id}` | | Image to video | `/kling/v1/videos/image2video/{task_id}` | | Motion Control | `/kling/v1/videos/motion-control/{task_id}` | | Multi-image video | `/kling/v1/videos/multi-image2video/{task_id}` | | Video effects | `/kling/v1/videos/effects/{task_id}` | | Video extension | `/kling/v1/videos/video-extend/{task_id}` | | Avatar video | `/kling/v1/videos/avatar/image2video/{task_id}` | For the full parameter reference, see the [official Kling documentation](https://kling.ai/document-api). # Identify faces for Kling lip-sync Source: https://apidoc.cometapi.com/api/video/kling/lip-sync api/openapi/video/kling/post-lip-sync.openapi.json POST /kling/v1/videos/identify-face Use Kling Lip-Sync API (POST /kling/v1/videos/identify-face) to detect faces in a video and drive accurate lip-sync video generation workflows. Use this endpoint to identify faces in a source video before you run a downstream lip-sync workflow. ## What this route returns * A `session_id` that groups the current face-detection result * A `face_data` array with one or more detected faces * Per-face metadata such as `face_id`, preview image, and time range ## When to use it * Send exactly one source: `video_id` for a completed Kling video, or `video_url` for a hosted MP4 or MOV * Before you build a lip-sync request for a video with multiple people on screen * When you need to choose a specific face instead of relying on auto-selection * When you want to preview face coverage before starting a more expensive task For the complete parameter reference, see the [official Kling documentation](https://kling.ai/document-api/apiReference/model/lipSync). # Create a Kling Motion Control task Source: https://apidoc.cometapi.com/api/video/kling/motion-control api/openapi/video/kling/post-motion-control.openapi.json POST /kling/v1/videos/motion-control Create a Kling Motion Control task from a character image and a reference motion video with the compatible CometAPI route. Use this endpoint to create a Motion Control task from a character image and a reference video. This page describes the compatible Motion Control route. Kling Video 3.0 Motion Control uses a separate API contract. ## Required media `image_url` accepts a public URL or a raw Base64 string. * Use a JPG, JPEG, or PNG image that is 10 MB or smaller. * Make each image dimension from 300 through 65,536 pixels. * Use an aspect ratio from 1:2.5 through 2.5:1. * Send Base64 as the raw encoded string without a `data:image/...;base64,` prefix. * Show one unobstructed character with body framing that matches the motion reference. `video_url` accepts a public MP4 or MOV URL. * Use a video that is 100 MB or smaller. * Make the short edge at least 340 pixels. * Make the long edge no more than 3850 pixels. * Use a continuous shot with one visible character. * Avoid cuts, camera changes, and excessively fast motion. Follow the duration limits and inspect the nested terminal `task_status`. An outer HTTP 200 or response `code: 0` confirms the query response, not a successful generation result. ## Set the orientation value `character_orientation` is required and accepts `image` or `video`. | Value | Reference video duration | | ------- | ------------------------ | | `image` | 3–10 seconds | | `video` | 3–30 seconds | If you use `element_list`, then set `character_orientation` to `video`. ## Choose the model and mode The compatible route accepts `kling-v2-6` and `kling-v3`. Both model values accept both mode values: | Model | `std` | `pro` | | ------------ | -------- | -------- | | `kling-v2-6` | Accepted | Accepted | | `kling-v3` | Accepted | Accepted | If you omit `model_name`, the request uses `kling-v2-6`. If you omit `mode`, the request uses `std`. The `kling-v3` value keeps the compatible request shape described on this page; it does not select the separate Kling 3.0 path-version contract. The compatible contract does not guarantee a fixed output resolution. Inspect each returned video if your application requires specific dimensions. `keep_original_sound` accepts `yes` or `no`. If you omit this field, the request uses `yes`. ## Task flow Send the source image, reference video, and orientation value. Select a model, mode, and sound value or use their documented defaults. Store the returned `task_id`. Use [Get a Kling task](./individual-queries) with the returned `task_id`. Continue until the status is `succeed` or `failed`. Download and store the result promptly. Kling's compatible API documentation states that generated videos are cleared after 30 days. Do not rely on the returned URL remaining accessible for the full 30 days. ## Optional fields | Field | Structure | Constraint | | ------------------ | --------------------------------------------------- | ----------------------------------------------------------------------------------------------------------- | | `prompt` | String, maximum 2500 characters | Optional text field in the compatible request structure. | | `callback_url` | URI string or empty string | Omit the field or use an empty string when no callback URI is configured. | | `external_task_id` | String that is unique for your account | Correlates the task with your application. It does not replace the returned `task_id` for CometAPI queries. | | `element_list` | Array with at most one `{"element_id": 123}` object | Combine this field only with `character_orientation: "video"`. | | `watermark_info` | `{"enabled": boolean}` | The compatible watermark structure contains only the `enabled` Boolean. | ## Callback structure The Legacy callback schema has the following structure: ```json theme={null} { "task_id": "", "task_status": "succeed", "task_status_msg": "", "created_at": 1785398400000, "updated_at": 1785398460000, "final_unit_deduction": "", "final_balance_deduction": { "quota": "", "list_price": "" }, "task_info": { "external_task_id": "" }, "task_result": { "videos": [ { "id": "", "url": "https://media.example.com/.mp4", "duration": "6.4" } ] } } ``` The callback status can be `submitted`, `processing`, `succeed`, or `failed`. Terminal result fields are present only when returned for the terminal state. ## Result fields | Field | Type | Description | | ------------------------------------ | ----------------------------------------- | --------------------------------------------------------- | | `task_result.videos[].id` | String | Generated video ID. | | `task_result.videos[].url` | URI string | Generated video delivery URL. | | `task_result.videos[].watermark_url` | URI string | Watermarked video delivery URL when the task returns one. | | `task_result.videos[].duration` | String | Generated video duration in seconds. | | `final_unit_deduction` | String | Final unit deduction value returned with the task. | | `final_balance_deduction` | `{"quota": string, "list_price": string}` | Final balance deduction values returned with the task. | The task status is `submitted`, `processing`, `succeed`, or `failed`. See the [Kling Motion Control API reference](https://kling.ai/document-api/api/video/motion-control/legacy) and [Kling callback protocol](https://kling.ai/document-api/api/get-started/callbacks) for API details. # Create a Kling multi-image video task Source: https://apidoc.cometapi.com/api/video/kling/multi-image-to-video api/openapi/video/kling/post-multi-image-to-video.openapi.json POST /kling/v1/videos/multi-image2video Create Kling videos from multiple images via CometAPI POST /kling/v1/videos/multi-image2video, with motion control and output settings for generation. Use this endpoint when one source image is not enough and you want Kling to build motion from multiple image references. ## Before you call it * Prepare 1 to 4 images in `image_list` * Use images that meet Kling pixel requirements; tiny thumbnails are rejected by the generation task * Omit `model_name` unless you specifically need to select a route-compatible model * Keep the first test simple: a short prompt, `duration: 5`, no extra callback settings * Do not send image-to-video mask fields such as `static_mask` or `dynamic_masks` on this route ## Task flow Send the image list, prompt, and duration, then save the returned Kling `task_id`. Continue with [Get a Kling task](./individual-queries) until the task reaches a terminal state. Store the finished video if you need retention beyond the provider delivery URL. For the complete parameter reference, see the [official Kling documentation](https://kling.ai/document-api/apiReference/model/multiImageToVideo). # Add Kling video selection Source: https://apidoc.cometapi.com/api/video/kling/multimodal-video-editing/add-video-selection api/openapi/video/kling/multimodal-video-editing/post-add-video-selection.openapi.json POST /kling/v1/videos/multi-elements/add-selection Use Kling Add Video Selection endpoint to add selection elements in multi-element video editing, enabling targeted edits and scene control via CometAPI. Use this endpoint to mark the video region you want the multimodal editor to operate on. ## How selection works * `session_id` comes from [Initialize Video for Editing](./initialize-video-for-editing) * Use the same account and exact `session_id` returned by initialization * `frame_index` selects the frame where you place points * `points` are normalized coordinates between `0` and `1` * Kling documents up to 10 marked frames and up to 10 points per frame ## Workflow role Start with [Initialize Video for Editing](./initialize-video-for-editing) to get a valid `session_id`. Call this endpoint as you build the region to edit. Use [Preview Selected Video Area](./preview-selected-video-area) before final submission. For the complete parameter reference, see the [Kling API documentation](https://kling.ai/document-api/apiReference/model/multiElements). # Clear Kling video selection Source: https://apidoc.cometapi.com/api/video/kling/multimodal-video-editing/clear-video-selection api/openapi/video/kling/multimodal-video-editing/post-clear-video-selection.openapi.json POST /kling/v1/videos/multi-elements/clear-selection Clear active element selections in Kling multimodal video editing via CometAPI POST /kling/v1/videos/multi-elements/clear-selection for clean edits. Use this utility endpoint to clear the current selection state for a multimodal editing session. ## When to use it * Your current selection is wrong and you want to start over * You want to rebuild the edit region before previewing or submitting the final task ## Workflow role * Requires only the `session_id` created by [Initialize Video for Editing](./initialize-video-for-editing) * Use the same account and exact `session_id` returned by initialization * Usually followed by a fresh call to [Add Video Selection](./add-video-selection) For the complete parameter reference, see the [Kling API documentation](https://kling.ai/document-api/apiReference/model/multiElements). # Create a Kling multimodal edit task Source: https://apidoc.cometapi.com/api/video/kling/multimodal-video-editing/create-task api/openapi/video/kling/multimodal-video-editing/post-create-task.openapi.json POST /kling/v1/videos/multi-elements Create a Kling multimodal video editing task via CometAPI: POST /kling/v1/videos/multi-elements to combine multiple elements and generate videos asynchronously. Use this endpoint to submit the final multimodal video-editing job after your session and selections are ready. ## Full workflow Start with [Initialize Video for Editing](./initialize-video-for-editing) to obtain the `session_id` for the clip you want to edit. Use [Add Video Selection](./add-video-selection) and, when needed, [Preview Selected Video Area](./preview-selected-video-area) to refine the edit region. Send the `session_id`, `edit_mode`, final `prompt`, and any optional generation settings through this endpoint, then save the returned task id for status checks. ## Before you call it * Make sure the selection session is already initialized * Confirm your region selection is correct before spending a generation call * Run selection follow-up calls on the same account and with the exact `session_id` returned by initialization * Set `edit_mode` to `addition`, `swap`, or `removal` * Provide `image_list` for `addition` and `swap`; omit `image_list` for `removal` * Send `duration` as a string such as `"5"` or `"10"`; examples pass `"5"` explicitly * Treat this route as the final generation step, not the setup step * Add `image_list`, `negative_prompt`, `mode`, `duration`, `callback_url`, or `external_task_id` only when the edit workflow needs them For the complete parameter reference, see the [Kling API documentation](https://kling.ai/document-api/apiReference/model/multiElements). # Delete Kling video selection Source: https://apidoc.cometapi.com/api/video/kling/multimodal-video-editing/delete-video-selection api/openapi/video/kling/multimodal-video-editing/post-delete-video-selection.openapi.json POST /kling/v1/videos/multi-elements/delete-selection Use Kling Delete Video Selection API to remove selected elements from a multi-elements video edit via CometAPI, supporting multimodal video workflows. Use this utility endpoint to remove selection state from a multimodal editing session before you rebuild or abandon the current edit area. ## When to use it * You want to remove the current selection record instead of continuing with it * You are cleaning up an editing pass before marking a new target area ## Workflow role * Requires the `session_id` from [Initialize Video for Editing](./initialize-video-for-editing) * Requires the `frame_index` and 0-1 percentage `points` for the selection points you want to delete * Typically followed by [Add Video Selection](./add-video-selection) or by ending the session without generating For the complete parameter reference, see the [Kling API documentation](https://kling.ai/document-api/apiReference/model/multiElements). # Initialize a Kling editing session Source: https://apidoc.cometapi.com/api/video/kling/multimodal-video-editing/initialize-video-for-editing api/openapi/video/kling/multimodal-video-editing/post-initialize-video-for-editing.openapi.json POST /kling/v1/videos/multi-elements/init-selection Initialize video elements via Kling init-selection endpoint in CometAPI to start multimodal editing with selectable regions and timestamps. Use this endpoint to open a video-editing session and obtain the `session_id` required by all later multimodal editing steps. ## Choose one input path * Kling-generated video: send `video_id` * External or already-hosted video: send `video_url` * Do not send both input paths at the same time * Do not send the parent `task_id` here; save the returned `session_id` for the next steps ## Workflow role Submit the source clip and save the returned `session_id`. Continue with [Add Video Selection](./add-video-selection) to define the region you want to edit. After selection is ready, continue with [Create Task](./create-task). For the complete parameter reference, see the [Kling API documentation](https://kling.ai/document-api/apiReference/model/multiElements). # Preview Kling video selection Source: https://apidoc.cometapi.com/api/video/kling/multimodal-video-editing/preview-selected-video-area api/openapi/video/kling/multimodal-video-editing/post-preview-selected-video-area.openapi.json POST /kling/v1/videos/multi-elements/preview-selection Use the Preview Selected Video Area endpoint to render a fast preview for chosen regions in Kling multimodal video edits via CometAPI. Use this endpoint to preview the selected region before you submit the final multimodal edit task. ## Why preview matters * It lets you verify that the selection points cover the intended object or area * It helps catch bad masks before you spend a generation call * It is the safest checkpoint between selection editing and final task creation ## Workflow role Start with [Initialize Video for Editing](./initialize-video-for-editing) and keep the returned `session_id` on the same account. Use [Add Video Selection](./add-video-selection) until the region is close to correct. Call this endpoint, then continue to [Create Task](./create-task) only after the selection looks right. For the complete parameter reference, see the [Kling API documentation](https://kling.ai/document-api/apiReference/model/multiElements). # Get a Kling Omni video Source: https://apidoc.cometapi.com/api/video/kling/omni-query api/openapi/video/kling/get-omni-query.openapi.json GET /kling/v1/videos/omni-video/{task_id} Use CometAPI GET /kling/v1/videos/omni-video/{task_id} to get Kling Omni video task status and results by task_id. Use this endpoint after you create a Kling Omni task. It returns the task state and final video URLs when the task succeeds. ## Check these fields first * `code`, `message`, and `request_id` for the query acknowledgement * `data.task_status` for the task state, such as `submitted`, `processing`, `succeed`, or `failed` * `data.task_result.videos[0].url` for the finished MP4 URL * `data.task_result.videos[0].watermark_url` for the watermarked MP4 URL when requested ## Polling pattern Start with [Create a Kling Omni video](./omni-video) and store the returned `task_id`. Keep querying until `data.task_status` reaches `succeed` or `failed`. When the task succeeds, download or copy the final video URL promptly. # Create a Kling Omni video Source: https://apidoc.cometapi.com/api/video/kling/omni-video api/openapi/video/kling/post-omni-video.openapi.json POST /kling/v1/videos/omni-video Use CometAPI POST /kling/v1/videos/omni-video to create Kling O1 video tasks and track status with the Omni query route. Use this endpoint for the O1-compatible Kling Omni workflow exposed by CometAPI, including text-to-video and first-frame image-referenced generation. For the complete provider parameter reference, see the [Kling Omni Video documentation](https://kling.ai/document-api/api/video/o1/video-omni). ## Choose the input mode * Text-to-video: send `prompt`, `mode`, `aspect_ratio`, and `duration` * First-frame image reference: add `image_list` items with `image_url` and `type: first_frame`, then reference the image in `prompt` as `<<>>` * Watermarked output: add `watermark_info.enabled: true` when you need a watermarked video URL in the query response * Model ID: omit `model_name` to use the route default, or send a tested Omni Video model ID such as `kling-video-o1` or `kling-v3-omni` ## Duration and aspect ratio | Setting | Supported values | Default | Boundary behavior | | ---------------------------------------- | --------------------- | ------------- | ----------------------------------------------------------------------------------------------------------- | | `duration` for text or first-frame video | `"5"`, `"10"` | `"5"` | Send the value as a string and use one of the two fixed generation lengths. | | `aspect_ratio` | `16:9`, `9:16`, `1:1` | `16:9` | Required when no first-frame image controls the frame. | | `mode` | `std`, `pro` | route default | Send `std` for standard generation or `pro` only when your selected model supports the higher-quality mode. | Kling Omni does not expose an exact `size` field. Treat `aspect_ratio` as a frame-shape request; a `16:9` text-to-video request can render as full-HD `1920x1080`. ## Task flow Submit the request and store the returned `task_id`. Continue with [Get a Kling Omni video](./omni-query) until the task finishes. Move the returned MP4 URL into your own storage if you need durable access. # Create Kling text-to-audio Source: https://apidoc.cometapi.com/api/video/kling/text-to-audio api/openapi/video/kling/post-text-to-audio.openapi.json POST /kling/v1/audio/text-to-audio Use Kling Text to Audio API in CometAPI to convert text prompts into audio with voice style controls, duration options, and streaming-ready output. Use this endpoint to generate a short audio clip from a text prompt through Kling. ## Before you call it * Keep `prompt` concise and direct * Start with `duration` between 3 and 10 seconds * Treat `callback_url` and `external_task_id` as optional integration helpers, not core requirements ## Task flow Send the text prompt and duration, then save the returned task id. Continue with [Get a Kling task](./individual-queries) using the Kling audio query path until the task reaches a terminal state. Persist the final audio asset if you need it beyond the provider delivery window. For the complete parameter reference, see the [official Kling documentation](https://app.klingai.com/global/dev/document-api/apiReference/model/textToAudio). # Create a Kling text-to-video task Source: https://apidoc.cometapi.com/api/video/kling/text-to-video api/openapi/video/kling/post-text-to-video.openapi.json POST /kling/v1/videos/text2video Generate videos from text prompts with Kling via CometAPI POST /kling/v1/videos/text2video, then track task status and retrieve results by task ID. Use this endpoint to create a Kling text-to-video task from a prompt. It starts an async job rather than returning a finished video immediately. ## First working request * Send a short prompt first * Start with the `kling-v3` example, then choose another `model_name` from the OpenAPI enum when you need a different model track * Add `aspect_ratio`, `duration`, `mode`, or `sound` only after the basic flow works * Set `callback_url` if you want push delivery instead of pure polling * Use `sound: off` when you want a deterministic no-audio first request on models that support generated sound ## Model naming Use ordinary Kling video model IDs on this endpoint. Keep Omni model IDs for [Omni Video](./omni-video). ## Duration and aspect ratio | Setting | Supported values | Default | Boundary behavior | | -------------- | --------------------- | ------------- | ---------------------------------------------------------- | | `duration` | `5`, `10` | `5` | Other values are outside the text-to-video request shape. | | `aspect_ratio` | `16:9`, `9:16`, `1:1` | `16:9` | Use the ratio that matches your delivery surface. | | `mode` | `std`, `pro` | `std` | `pro` improves quality and costs more. | | `sound` | `on`, `off` | model default | Applies only to model tracks that support generated audio. | This endpoint does not expose a separate resolution token or exact `size` field. The requested aspect ratio controls the output frame shape. | `aspect_ratio` | Typical rendered `WxH` | | -------------- | ---------------------- | | `16:9` | `1280x720` | | `9:16` | `720x1280` | | `1:1` | `960x960` | ## Task flow Create the task through this endpoint and save the returned Kling task id. Check progress through [Get a Kling task](./individual-queries) until the task reaches a terminal state. Once Kling returns the finished asset metadata, move the result into your own storage if you need long retention. For the full parameter matrix and model-track details, refer to the [official Kling documentation](https://kling.ai/document-api/apiReference/model/textToVideo). # Create Kling speech Source: https://apidoc.cometapi.com/api/video/kling/tts api/openapi/video/kling/post-tts.openapi.json POST /kling/v1/audio/tts Call Kling TTS via CometAPI POST /kling/v1/audio/tts to convert text to speech with multilingual voices, plus fixes for voice_id not found errors. ## TTS The Kling TTS (Text-to-Speech) API provides high-quality text-to-speech services, supporting multiple languages and voice options. ### Reference documentation * **API Reference**: [Kling TTS API Documentation](https://app.klingai.com/global/dev/document-api/apiReference/model/TTS) * **Voice ID List**: [Available Voice ID Reference](https://docs.qingque.cn/s/home/eZQDvafJ4vXQkP8T9ZPvmye8S?identityId=2E1MlYrrPk4) *** ## Common issues ### Voice id not found error **Issue Description**: When `voice_id` does not match `voice_language`, the API will return the following error: ```json theme={null} { "message": "Voice id not found", "data": { "data": { "code": 1201, "message": "Voice id not found", "request_id": "ed47a82c-804b-45f3-bde9-926039cd25c0" }, "message": "Voice id not found" } } ``` **Solution**: Please ensure that the selected `voice_id` supports your specified `voice_language`. Refer to the [Voice ID List](https://docs.qingque.cn/s/home/eZQDvafJ4vXQkP8T9ZPvmye8S?identityId=2E1MlYrrPk4) to check which languages each voice ID supports. # Apply Kling video effects Source: https://apidoc.cometapi.com/api/video/kling/video-effects api/openapi/video/kling/post-video-effects.openapi.json POST /kling/v1/videos/effects Use the Kling Video Effects API via CometAPI to apply stylized effects to videos with POST /kling/v1/videos/effects and control effect parameters. Use this endpoint to apply one of Kling's preset effect scenes and turn the input assets into a new short video. ## Choose an effect scene * Single-image effects use `effect_scene` plus `input.image` and `input.duration` * Two-person interaction effects use `effect_scene` plus `input.images` with exactly two images * Input images must meet Kling pixel requirements; tiny thumbnails are rejected by the generation task * The exact asset shape depends on the selected effect, but the request always wraps effect settings inside `input` * Use an effect scene that is currently available in Kling; CometAPI rejects unknown `effect_scene` values * Avoid relying on a fixed public enum list; effect availability changes by model track and scene family ## Task flow Send `effect_scene` plus the matching `input` object and store the returned task id. Continue with [Get a Kling task](./individual-queries) until the effect job finishes. Download or mirror the finished effect video if you need stable retention. For the complete parameter reference, see the [official Kling documentation](https://kling.ai/document-api/apiReference/model/videoEffects). # Extend a Kling video Source: https://apidoc.cometapi.com/api/video/kling/video-extension api/openapi/video/kling/post-video-extension.openapi.json POST /kling/v1/videos/video-extend Extend Kling-generated videos via POST /kling/v1/videos/video-extend using task_id and video_id; run as a sub-task on the parent account. Use this endpoint to extend an existing Kling video as a follow-up task. ## Before you call it * Start from a finished Kling video result * Pass the `video_id` from the parent task result * Pass the parent `task_id` together with the `video_id` * Use a source video that is extension-compatible; unsupported source videos return HTTP 400 instead of creating an extension task * A completed 5 s Kling v1 or v1-6 text-to-video or image-to-video parent is a safer starting point for extension compatibility * Add `prompt`, `negative_prompt`, or `cfg_scale` only when you need to steer the continuation * Run the extension on the same account context as the parent task * Trigger the extension promptly before parent-task resources expire ## Task flow Create the original Kling video and wait until its result is available. Send the parent `task_id`, `video_id`, and optional prompt, then save the returned task id. Continue with [Get a Kling task](./individual-queries) until the extended video reaches a terminal state. For the complete parameter reference, see the [official Kling documentation](https://kling.ai/document-api/apiReference/model/videoDuration). # Create Kling video-to-audio Source: https://apidoc.cometapi.com/api/video/kling/video-to-audio api/openapi/video/kling/post-video-to-audio.openapi.json POST /kling/v1/audio/video-to-audio Convert Kling videos into high-quality audio via CometAPI’s Video to Audio endpoint, with configurable output format, duration, and prompt control. Use this endpoint to generate an audio result from a source video. ## Before you call it * Send either `video_id` or `video_url`, but not both * Use `video_url` when the source clip did not come from Kling originally * Keep `callback_url` and `external_task_id` optional unless your integration needs them ## Task flow Send either the Kling `video_id` or an accessible `video_url`, then save the returned task id. Continue with [Get a Kling task](./individual-queries) using the Kling audio query path until the task reaches a terminal state. Store the final audio asset if you need stable retention or downstream processing. For the complete parameter reference, see the [official Kling documentation](https://app.klingai.com/global/dev/document-api/apiReference/model/videoToAudio). # Create an Omni video from text, image, or video Source: https://apidoc.cometapi.com/api/video/omni/create api/openapi/video/omni/post-create.openapi.json POST /v1/videos Create a beta Omni text-to-video, image-to-video, or reference-video editing task through CometAPI with POST /v1/videos, then poll the task and download the completed MP4 file. Use this beta endpoint to create a text-to-video, image-to-video, or video-to-video task. The API returns a task ID immediately, so store the returned `id` and poll the task until it reaches a terminal status. Choose the request content type that matches the input mode. Send text-to-video and image-to-video controls as `multipart/form-data` fields. Send a reference-video edit as an `application/json` body. ## Choose an input mode | Goal | Content type | Required fields | Optional fields | | -------------- | --------------------- | ------------------------------------ | --------------------------------------- | | Text-to-video | `multipart/form-data` | `model`, `prompt` | `seconds`, `aspect_ratio`, `resolution` | | Image-to-video | `multipart/form-data` | `model`, `prompt`, `input_reference` | `seconds`, `aspect_ratio`, `resolution` | | Video-to-video | `application/json` | `model`, `prompt`, `video` | `seconds`, `aspect_ratio`, `resolution` | The text-to-video and image-to-video examples use `model=omni-fast`. The video-to-video examples use `model=omni-fast-v2v`. Use [List available models](/guides/how-to-list-available-models) to confirm that a model ID is visible to your API key. ## Animate a reference image For image-to-video, use `model=omni-fast` and upload one PNG file in the multipart `input_reference` field. The field remains optional for text-to-video, but it is required when a reference image should drive the generated video. Focus the `prompt` on the motion to add and explicitly name the colors, shapes, subjects, or composition that the result should preserve. The code sample selector includes Shell, Python, and JavaScript examples that upload `reference.png` from the working directory and create the task. This request shape covers one uploaded PNG. It does not define URL input, other image formats, multiple reference images, or file-size limits. ## Edit a reference video For video-to-video, encode a local MP4 file as base64 and prefix the encoded bytes with `data:video/mp4;base64,`. Send the complete data URL in the `video` field. Describe the requested changes in `prompt`. Also name the subjects, objects, composition, or motion that the result should preserve. The code sample selector includes Shell, Python, and JavaScript examples that read `reference.mp4` from the working directory. This request shape covers an inline MP4 data URL. It does not define URL input, other video container formats, or file-size limits. ## Set duration, ratio, and resolution Omni is marked beta because generation stability can vary by input and selected route. Keep the first request small, then inspect the completed video before relying on a specific rendered duration or frame size. | Setting | Supported values | Default | Boundary behavior | | -------------- | ------------------------------------------ | --------------- | ------------------------------------------------------------------------------------------------------- | | `seconds` | Start with `4` | Route-dependent | Treat this as a requested duration and verify the completed MP4 because the output duration can differ. | | `aspect_ratio` | `16:9`, `9:16`, `1:1` | `16:9` | `9:16` can render portrait output. `1:1` can be accepted while rendering as landscape. | | `resolution` | Start with `720p`; `1080p` can be accepted | `720p` | Current production output can normalize to `720p` even when `1080p` is requested. | | Request | Observed completed frame | | --------------------------------------- | ------------------------ | | `resolution=720p`, `aspect_ratio=16:9` | `1280x720` | | `resolution=720p`, `aspect_ratio=9:16` | `720x1280` | | `resolution=720p`, `aspect_ratio=1:1` | `1280x720` | | `resolution=1080p`, `aspect_ratio=16:9` | `1280x720` | Because this endpoint is beta, treat `aspect_ratio` and `resolution` as generation preferences and verify the downloaded MP4 before depending on final pixels. ## Task flow Send the request with the content type for the selected input mode and store the returned `id`. Call [Retrieve an Omni video](./retrieve) until `status` is `completed` or `failed`. When the task is `completed`, call [Retrieve Omni video content](./retrieve-content) to download the MP4 file. # Retrieve an Omni video Source: https://apidoc.cometapi.com/api/video/omni/retrieve api/openapi/video/omni/get-retrieve.openapi.json GET /v1/videos/{task_id} Retrieve a beta Omni video task by task ID, including status, progress, timestamps, and the completed video URL. Use this endpoint after you create a beta Omni video task. It returns the task state and includes `video_url` after the task is completed. **Status:** Beta ## Check these fields * `status` tells you whether the task is `queued`, `in_progress`, `completed`, or `failed`. * `progress` is a coarse completion percentage. * `video_url` appears on completed responses. * `error` appears when a task fails. ## Polling flow Start with [Create an Omni video](./create) and store the returned `id`. Send the task ID to this endpoint until `status` reaches `completed` or `failed`. When `status` is `completed`, call [Retrieve Omni video content](./retrieve-content). # Download Omni video content Source: https://apidoc.cometapi.com/api/video/omni/retrieve-content api/openapi/video/omni/get-retrieve-content.openapi.json GET /v1/videos/{task_id}/content Download the completed MP4 file for a beta Omni video task through the content route. Use this endpoint to download the MP4 file for a completed beta Omni video task. If the task is still running, the API returns a JSON error instead of video bytes. **Status:** Beta ## Before you download * Create a task with [Create an Omni video](./create). * Poll with [Retrieve an Omni video](./retrieve) until `status` is `completed`. * Pass the same task ID to this endpoint. ## Store completed media The response body is binary `video/mp4` content. Save the bytes to your own storage when your application needs durable access to the generated media. # Create a Runway character performance Source: https://apidoc.cometapi.com/api/video/runway/official-format/control-a-character api/openapi/video/runway/official-format/post-control-a-character.openapi.json POST /runwayml/v1/character_performance Use CometAPI with Runway Control a character API to start character performance tasks from a reference video, driving facial expressions and body motion. Use this endpoint to transfer performance from a reference clip onto a character image or character video. ## Before you call it * Send the required `X-Runway-Version` header, for example `2024-11-06` * Use `model: act_two` * Provide one `character` asset and one `reference` asset as accessible HTTPS URLs * Start with `bodyControl: true` and a moderate `expressionIntensity` before tuning style ## Output ratio | Setting | Supported values | Default starting point | Boundary behavior | | ------- | -------------------------------------------------------------------------------------- | ---------------------- | --------------------------------------------------------------------------- | | `ratio` | `1280:720`, `720:1280`, or another ratio accepted by the selected Runway model/version | `1280:720` | Keep the character and reference assets close to the requested frame shape. | ## Task flow Create the task with your character asset, reference asset, and motion settings. Keep the returned `id`, because you need it for later polling. Continue with [Get a Runway task](./runway-to-get-task-details) until the task reaches a terminal state and provider metadata includes the finished output. ## Input roles * `character` is the subject you want to animate * `reference` is the source clip that provides facial performance or body motion * `bodyControl` decides whether motion transfer includes body movement in addition to expression transfer * `contentModeration` applies provider moderation thresholds to the request # Create a Runway video-to-video task Source: https://apidoc.cometapi.com/api/video/runway/official-format/generate-a-video-from-a-video api/openapi/video/runway/official-format/post-generate-a-video-from-a-video.openapi.json POST /runwayml/v1/video_to_video Use CometAPI Runway POST /runwayml/v1/video_to_video to start video-to-video generation tasks, set X-Runway-Version, and transform source clips. Use this endpoint to transform an existing source clip with Runway's video-to-video workflow. It starts an async task instead of returning the final output immediately. ## Before you call it * Prepare a source video that matches the provider's input requirements * Include the required `X-Runway-Version` header for the feature set you want * Start with one short prompt that describes the change, not a full storyboard ## Output ratio | Setting | Supported values | Default starting point | Boundary behavior | | ------- | -------------------------------------------------------------------------------------- | ---------------------- | ------------------------------------------------- | | `ratio` | `1280:720`, `720:1280`, or another ratio accepted by the selected Runway model/version | `1280:720` | Match the source clip orientation where possible. | This endpoint expects colon-separated `ratio` values. Use `1280:720` for `1280x720` output and `720:1280` for `720x1280`; `1280x720` is not accepted on every Runway video-to-video route. ## Task flow Start the task from this endpoint and save the returned task id. Use [Get a Runway task](./runway-to-get-task-details) until the task reaches a terminal state. Download or persist the finished asset through your normal media pipeline. # Create a Runway image Source: https://apidoc.cometapi.com/api/video/runway/official-format/generate-an-image-from-text api/openapi/video/runway/official-format/post-generate-an-image-from-text.openapi.json POST /runwayml/v1/text_to_image Use POST /runwayml/v1/text_to_image to start a Runway task that generates images from a text prompt, with X-Runway-Version support. Use this endpoint to create a Runway image-generation task. ## Usage notes * Send the required `X-Runway-Version` header, for example `2024-11-06` * Use `model: gen4_image` * This route requires at least one `referenceImages` item — a text-only request returns `reference_images_empty` ## Task flow Send `promptText`, `ratio`, `model`, and at least one `referenceImages` object. Keep the returned `id`, because this route is asynchronous. Use [Get a Runway task](./runway-to-get-task-details). If an immediate poll returns `task_not_exist`, wait a few seconds and retry. # Create a Runway image-to-video task Source: https://apidoc.cometapi.com/api/video/runway/official-format/runway-images-raw-video api/openapi/video/runway/official-format/post-runway-images-raw-video.openapi.json POST /runwayml/v1/image_to_video Use CometAPI to call Runway image_to_video and convert a still image URL into raw video output, with X-Runway-Version support for compatibility. Use this endpoint to animate one source image into a Runway video. ## Before you call it * Send the required `X-Runway-Version` header, for example `2024-11-06` * Use `model: gen3a_turbo` * Provide a stable HTTPS `promptImage` * Start with `duration: 5` and a supported ratio value for the selected Runway model/version ## Duration and ratio | Setting | Supported values | Default starting point | Boundary behavior | | ------------------------------------------- | ---------------------------------------------------------------------------------------------------------------- | ---------------------- | --------------------------------------------------------------------------------------------------------------- | | `duration` | Runway model/version dependent; use `5` or `10` for the broadest compatibility | `5` | CometAPI forwards the value to Runway. If the selected model/version rejects it, retry with `5`. | | `ratio` with `X-Runway-Version: 2024-11-06` | Runway model/version dependent resolution-style values such as `1280:768`, `768:1280`, `1280:720`, or `720:1280` | `1280:768` | Request values can normalize in the completed media; inspect the finished video before relying on exact pixels. | | `ratio` with older compatibility versions | `16:9`, `9:16`, or the resolution-style values accepted by the selected model/version | `16:9` or `1280:768` | Prefer the current Runway resolution-style values for production integrations. | Runway official-format requests use `ratio`, not `size`. Read resolution-style ratio values as their `WxH` equivalent: `1280:720` targets `1280x720`, `720:1280` targets `720x1280`, and `1280:768` can still render as `1280x720` depending on the selected model/version. ## Task flow Create the task with a source image and an optional short motion prompt. Save the task `id` for later polling. Use [Get a Runway task](./runway-to-get-task-details). If the first poll returns `task_not_exist`, wait a few seconds and retry. # Get a Runway task Source: https://apidoc.cometapi.com/api/video/runway/official-format/runway-to-get-task-details api/openapi/video/runway/official-format/get-runway-to-get-task-details.openapi.json GET /runwayml/v1/tasks/{id} Use CometAPI to call GET /runwayml/v1/tasks/{id} and fetch Runway video generation task status, progress, outputs, and metadata by task ID. Use this endpoint to inspect a Runway task by id. ## Check these fields first * `id` for the task identifier * `status` for the current task state * `output` for finished asset URLs when the task succeeds * `failure` and `failureCode` when the task fails ## When to use it * After calling an official-format Runway task creation page such as text-to-image, image-to-video, or video-to-video ## Retry behavior * A freshly created task may briefly return `task_not_exist` * Wait a few seconds and retry before treating the task id as invalid * Once the task is visible, continue polling this endpoint until it returns a terminal state or finished output. # Download Vidu video content Source: https://apidoc.cometapi.com/api/video/vidu/retrieve-content api/openapi/video/vidu/get-retrieve-content.openapi.json GET /v1/videos/{task_id}/content Download the completed MP4 file for a Vidu video task through the content route. Use this endpoint to download the MP4 file for a completed Vidu video task. If the task is still running, the API returns a JSON error instead of video bytes. ## Before you download * Create a task with [Create a Vidu video](./create). * Poll with [Retrieve a Vidu video](./retrieve) until `status` is `completed`. * Pass the same task ID to this endpoint. ## Store completed media The response body is binary `video/mp4` content. Save the bytes to your own storage when your application needs durable access to the generated media. # Connect Activepieces to CometAPI Source: https://apidoc.cometapi.com/integrations/activepieces Use this guide to connect Activepieces to CometAPI by setting the base URL, API key, and model or provider options. [Activepieces](https://cloud.activepieces.com/) is an open-source automation platform. With the built-in CometAPI connector, you can add AI steps to any workflow in seconds. ## Prerequisites * An [Activepieces](https://cloud.activepieces.com/) account * A [CometAPI](https://www.cometapi.com) account with an active API key ## Setup Log in to the [CometAPI dashboard](https://www.cometapi.com/console). Click **Add API Key** and copy your key. CometAPI dashboard — Add API Key button CometAPI API key details and base URL In your Activepieces project, click **Create Flow** → **From Scratch**. Click the **+** button on the canvas, search for `cometapi`, and select **Ask CometAPI**. Activepieces canvas with the + button to add a step Search results showing the CometAPI connector Ask CometAPI step selected in the connector list Paste your API key into the **API Key** field. Select the current model you want to use and fill in your prompt. CometAPI step — API key and model selection Prompt configuration for the Ask CometAPI step Click **Test** to run the step. A successful response confirms the integration is working. Successful test response from the CometAPI step If the test fails, verify your API key is correct and your account has available balance. Contact [CometAPI support](https://www.cometapi.com) if the issue persists. # Use Agno with CometAPI Source: https://apidoc.cometapi.com/integrations/agno Use this guide to connect Agno agents to CometAPI with the CometAPI model provider, API key, and model ID. [Agno](https://docs.agno.com/) lets you build and run AI agents in Python. Agno includes an official `CometAPI` model provider, so you can use CometAPI directly from `agno.models.cometapi` without creating a custom adapter. ## Prerequisites * Python 3.10+ * The Agno Python package * A CometAPI account with an active API key — [get yours in the dashboard](https://www.cometapi.com/console/token) ## Configure the integration Install Agno in your Python environment: ```bash theme={null} pip install -U agno ``` Store your CometAPI API key in the `COMETAPI_KEY` environment variable: ```bash theme={null} read -rsp "CometAPI API key: " COMETAPI_KEY printf '\n' export COMETAPI_KEY ``` Use Agno's official `CometAPI` provider: ```python theme={null} from agno.agent import Agent from agno.models.cometapi import CometAPI agent = Agent( model=CometAPI(id="your-model-id"), markdown=True, ) agent.print_response("Write a short product update in three bullet points.") ``` Replace `your-model-id` with a current model ID from the [CometAPI Models page](/overview/models). Save the example as `agent.py`, then run it from the same shell session: ```bash theme={null} python agent.py ``` A successful response confirms that Agno is sending model calls through CometAPI. ## How Agno connects to CometAPI Agno's official `CometAPI` provider reads `COMETAPI_KEY` from your environment and uses `https://api.cometapi.com/v1` as the default base URL. It extends Agno's OpenAI-compatible model interface internally, but your application code should import and instantiate `CometAPI`. You can also pass the API key or base URL explicitly when your runtime cannot read environment variables: ```python theme={null} import os from agno.agent import Agent from agno.models.cometapi import CometAPI agent = Agent( model=CometAPI( id="your-model-id", api_key=os.environ["COMETAPI_KEY"], base_url="https://api.cometapi.com/v1", ) ) agent.print_response("Summarize the benefits of a unified AI API.") ``` ## List available models Agno's provider exposes `get_available_models()` for checking the model IDs available through your CometAPI account: ```python theme={null} from agno.models.cometapi import CometAPI model = CometAPI() available_models = model.get_available_models() print(available_models) ``` ## Troubleshooting Confirm that `COMETAPI_KEY` is set in the same shell session that runs `agent.py`. If the variable is missing, Agno raises an authentication error before sending the model request. Confirm that the `id` value matches a model ID from the [CometAPI Models page](/overview/models). You can also call `CometAPI().get_available_models()` to inspect model availability from your account. ## Related resources * [Agno CometAPI provider documentation](https://docs.agno.com/models/providers/gateways/cometapi/overview) * [Agno CometAPI provider source](https://github.com/agno-agi/agno/blob/main/libs/agno/agno/models/cometapi/cometapi.py) * [Agno CometAPI cookbook](https://github.com/agno-agi/agno/tree/main/cookbook/90_models/cometapi) * [CometAPI quick start](/overview/quick-start) * [CometAPI Models page](/overview/models) # Use AI SDK with CometAPI Source: https://apidoc.cometapi.com/integrations/ai-sdk Use this guide to configure AI SDK with CometAPI by setting the base URL, API key, and model or provider options. The [CometAPI provider for the AI SDK](https://github.com/cometapi-dev/ai-sdk-provider) gives you access to 500+ AI models through a unified TypeScript interface. Use it to add text generation, streaming, embeddings, and image generation to any Node.js or Edge runtime application. ## Supported features | Feature | Method | Status | | ---------------- | ---------------------- | --------- | | Text generation | `generateText()` | Supported | | Text streaming | `streamText()` | Supported | | Text embeddings | `textEmbeddingModel()` | Supported | | Image generation | `imageModel()` | Supported | ## Prerequisites * Node.js 18+ * A CometAPI account with an active API key — [get yours here](https://www.cometapi.com/console/token) Install `@cometapi/ai-sdk-provider` alongside the AI SDK core package: ```bash npm theme={null} npm install @cometapi/ai-sdk-provider ai ``` ```bash pnpm theme={null} pnpm add @cometapi/ai-sdk-provider ai ``` ```bash yarn theme={null} yarn add @cometapi/ai-sdk-provider ai ``` The provider reads the `COMETAPI_KEY` environment variable by default: ```bash theme={null} read -rsp "CometAPI API key: " COMETAPI_KEY printf '\n' export COMETAPI_KEY ``` Use environment variables to avoid hardcoding credentials in your source code. Import the default provider instance: ```typescript theme={null} import { cometapi } from '@cometapi/ai-sdk-provider'; ``` To override the API key, base URL, or other settings, use `createCometAPI`: ```typescript theme={null} import { createCometAPI } from '@cometapi/ai-sdk-provider'; const cometapi = createCometAPI({ apiKey: process.env.COMETAPI_KEY, // override env variable baseURL: 'https://api.cometapi.com/v1', // default }); ``` ## Usage ### Generate text Use `generateText()` for a single-shot response: ```typescript theme={null} import { cometapi } from '@cometapi/ai-sdk-provider'; import { generateText } from 'ai'; const { text } = await generateText({ model: cometapi('your-model-id'), prompt: 'What is CometAPI?', }); console.log(text); ``` ### Stream text Use `streamText()` for real-time chunked output: ```typescript theme={null} import { cometapi } from '@cometapi/ai-sdk-provider'; import { streamText } from 'ai'; const result = streamText({ model: cometapi('your-model-id'), prompt: 'Write a short story about AI.', }); for await (const chunk of result.textStream) { process.stdout.write(chunk); } ``` ### Generate embeddings Use `textEmbeddingModel()` to create vector embeddings: ```typescript theme={null} import { cometapi } from '@cometapi/ai-sdk-provider'; const model = cometapi.textEmbeddingModel('text-embedding-3-small'); // Single embedding const single = await model.doEmbed({ values: ['Hello, world!'] }); console.log('Dimensions:', single.embeddings[0].length); // Batch embeddings const batch = await model.doEmbed({ values: ['sunny day', 'rainy afternoon', 'cold winter night'], }); console.log('Count:', batch.embeddings.length); ``` ### Generate images Use `imageModel()` to generate images from text prompts: ```typescript theme={null} import { cometapi } from '@cometapi/ai-sdk-provider'; import { experimental_generateImage as generateImage } from 'ai'; const { image } = await generateImage({ model: cometapi.imageModel('your-model-id'), prompt: 'A beautiful sunset over mountains', }); ``` ## Provider configuration `createCometAPI` accepts the following options: | Option | Type | Default | Description | | --------- | ------------------------ | ----------------------------- | --------------------------- | | `apiKey` | `string` | `process.env.COMETAPI_KEY` | CometAPI API key | | `baseURL` | `string` | `https://api.cometapi.com/v1` | API base URL | | `headers` | `Record` | — | Custom request headers | | `fetch` | `FetchFunction` | — | Custom fetch implementation | ## Model methods The provider exposes several model constructors: | Method | Returns | Use case | | -------------------------------------- | ------------------ | ----------------------------------------- | | `cometapi(modelId)` | `LanguageModelV2` | Text generation and streaming (shorthand) | | `cometapi.chatModel(modelId)` | `LanguageModelV2` | Chat completions | | `cometapi.completionModel(modelId)` | `LanguageModelV2` | Text completions | | `cometapi.languageModel(modelId)` | `LanguageModelV2` | Alias for `chatModel` | | `cometapi.textEmbeddingModel(modelId)` | `EmbeddingModelV2` | Text embeddings | | `cometapi.imageModel(modelId)` | `ImageModelV2` | Image generation | Browse the full list of available model IDs on the [Models page](/overview/models). * **Model selection**: Any model from the [CometAPI model catalog](/overview/models) works with the corresponding model method — chat models via `cometapi()`, embedding models via `textEmbeddingModel()`, image models via `imageModel()`. * **Fine-tuning responses**: Pass `temperature`, `maxTokens`, and `topP` directly to `generateText()` or `streamText()`, e.g. `generateText(\{..., temperature: 0.7\})`. * **Error handling**: Wrap calls in `try/catch` to handle authentication errors, rate limits, or network issues. * **Security**: Never commit API keys to version control. Use environment variables or a secrets manager. * **Rate limits**: Monitor usage in the [CometAPI console](https://www.cometapi.com/console). ## Related resources * [CometAPI AI SDK Provider on GitHub](https://github.com/cometapi-dev/ai-sdk-provider) * [@cometapi/ai-sdk-provider on npm](https://www.npmjs.com/package/@cometapi/ai-sdk-provider) * [AI SDK documentation](https://ai-sdk.dev/docs) * [CometAPI quick start](/overview/quick-start) # Use AnythingLLM with CometAPI Source: https://apidoc.cometapi.com/integrations/anythingllm Use this guide to configure AnythingLLM with CometAPI by setting the base URL, API key, and model or provider options. [AnythingLLM](https://anythingllm.com/) is an all-in-one AI desktop app. By selecting **Generic OpenAI** as the provider, you can connect it to CometAPI and access 500+ models. ## Prerequisites * [AnythingLLM](https://anythingllm.com/) installed on your machine * A [CometAPI](https://www.cometapi.com) account with an active API key ## Setup Log in to the [CometAPI dashboard](https://www.cometapi.com/console). Click **Add API Key** and copy your key and base URL (`https://api.cometapi.com`). CometAPI dashboard — Add API Key CometAPI API key and base URL Open AnythingLLM **Settings** → **AI Providers** → **LLM Preferences**. Select **Generic OpenAI** as the model provider and enter `https://api.cometapi.com/v1` in the **URL** field. Paste your CometAPI key into the **API Key** field. Set **Token Context Window** and **Max Tokens** to match your chosen model, then enter the current model ID you want to use. AnythingLLM LLM Preferences with Generic OpenAI selected Base URL and API key fields filled in Model name and token settings configured Open a workspace and send a test message. A successful reply confirms the integration is working. AnythingLLM chat showing a successful response You can add multiple model names on the same configuration page. Check the [CometAPI model list](/overview/models) for supported identifiers. # Use avante.nvim with CometAPI Source: https://apidoc.cometapi.com/integrations/avante-nvim Use this guide to configure avante.nvim with CometAPI by setting the base URL, API key, and model or provider options. [avante.nvim](https://github.com/yetone/avante.nvim) is a Neovim plugin that brings AI coding assistance into your editor. Configure it to use CometAPI as the backend to access GPT, Claude, and other models. ## Prerequisites * [avante.nvim](https://github.com/yetone/avante.nvim) installed in Neovim * A [CometAPI](https://www.cometapi.com) account with an active API key ## Setup Log in to the [CometAPI dashboard](https://www.cometapi.com/console). Click **Add API Key** and copy your key and base URL (`https://api.cometapi.com`). CometAPI dashboard — Add API Key CometAPI API key and base URL Open your Neovim config file and set the API endpoint to `https://api.cometapi.com/v1`. Paste your CometAPI key into the `openai` key field. avante.nvim configuration file with CometAPI base URL and API key Reload Neovim and trigger avante.nvim. A successful response confirms the setup is working. # Connect BuildShip to CometAPI Source: https://apidoc.cometapi.com/integrations/buildship Use this guide to connect BuildShip to CometAPI by setting the base URL, API key, and model or provider options. BuildShip is a low-code visual backend builder. Use the community **CometAPI Text Generator** node to add AI-powered text generation to any workflow. ## Prerequisites * A CometAPI account with an active API key — [get yours here](https://www.cometapi.com/console/token) * A BuildShip account — [sign in here](https://app.buildship.com) Log in to the [CometAPI console](https://www.cometapi.com/console/token). Click **Add API Key** and copy your CometAPI API key. CometAPI dashboard showing the Add API Key button CometAPI API key details with base URL 1. In the BuildShip dashboard, click **Create a new workflow → From Scratch**. 2. On the canvas, click **Add Trigger** and select **REST API**. This generates a callable endpoint for the workflow. 1. Below the REST API trigger, click **+ Add a new step**. 2. In the node library search box, type `cometapi`. 3. From the **Community** list, select **CometAPI Text Generator**. BuildShip node library showing CometAPI Text Generator in search results CometAPI Text Generator node added to the canvas This step tells the node which key management system to use. 1. Click the node to open the **Node Editor** on the right. 2. Switch to the **Settings** tab. 3. In **Key-based Integration**, open the dropdown and select **CometAPI**. 4. Click the blue **Save** button in the top-right corner. Node Editor Settings tab with Key-based Integration set to CometAPI 1. In the Node Editor, switch to the **Inputs** tab (or click directly on the node). 2. Click the 🔑 key icon in the node's top-right corner to open the key dropdown. 3. Select **+ Bring your own Key**. 4. Enter a **Key ID** (e.g. `cometapi-key-1`) and paste your CometAPI API key in **Value**. 5. Click **Save**. Key management dialog with Key ID and Value fields filled in Node showing the key bound successfully In the node's **Inputs** tab: * **Instructions** (optional): set a system role, e.g. `You are a productivity assistant.` * **Prompt**: click the **``** icon, then select **Trigger → Body → prompt** to map the incoming request body. * **Advanced → Model**: enter the current model ID you want to use. CometAPI node with Instructions, Prompt, and Model configured 1. Below the CometAPI node, click **+ Add a new step** and select **Return Response**. 2. In the **Body** field, click **``** and select the `response` variable from the CometAPI Text Generator node. 3. Click **Test** in the upper-right corner, select **JSON** input format, and send: ```json theme={null} { "prompt": "hi" } ``` 4. A successful response in the **Result** panel confirms the workflow is working. BuildShip test panel showing a successful CometAPI response If the call fails, verify your API key and that the Key-based Integration is set to **CometAPI**, or contact [CometAPI support](https://www.cometapi.com). The **Key-based Integration** step (linking the node to CometAPI) is essential — skipping it will cause authentication errors even if your API key is correct. # Use ChatAll with CometAPI Source: https://apidoc.cometapi.com/integrations/chatall-translation Use this guide to configure ChatAll with CometAPI by setting the base URL, API key, and model or provider options. [ChatAll](https://github.com/ai-shifu/ChatALL) lets you send messages to multiple AI models simultaneously. Connect it to CometAPI to access GPT, Claude, Gemini, and more through a single key. ## Prerequisites * [ChatAll](https://github.com/ai-shifu/ChatALL/releases) installed * A [CometAPI](https://www.cometapi.com) account with an active API key ## Setup Log in to the [CometAPI dashboard](https://www.cometapi.com/console). Click **Add API Key** and copy your key and base URL (`https://api.cometapi.com`). CometAPI dashboard — Add API Key CometAPI API key and base URL Open ChatAll → **Settings** → **OpenAI**. Enter `https://api.cometapi.com/v1` in the **API Address** field, paste your CometAPI key into **API Key**, and click **Save**. ChatAll OpenAI settings with CometAPI base URL API key field filled in ChatAll settings Click the model selector to view and switch between available models. ChatAll model selection panel Models listed and selected in ChatAll # Use Chatbox with CometAPI Source: https://apidoc.cometapi.com/integrations/chatbox Use this guide to configure Chatbox with CometAPI by setting the base URL, API key, and model or provider options. [Chatbox](https://chatboxai.app/) is a cross-platform desktop client for AI models. Connect it to CometAPI using the OpenAI-compatible API settings. ## Prerequisites * [Chatbox](https://chatboxai.app/) installed * A [CometAPI](https://www.cometapi.com) account with an active API key ## Setup Log in to the [CometAPI dashboard](https://www.cometapi.com/console). Click **Add API Key** and copy your key and base URL (`https://api.cometapi.com`). CometAPI dashboard — Add API Key CometAPI API key and base URL Open Chatbox **Settings** → **Model**. Select **OpenAI API** as the provider, enter `https://api.cometapi.com` in the **API Domain** field, paste your key into **API Key**, and click **Save**. Chatbox settings showing OpenAI API selected and CometAPI domain entered Send a test message in Chatbox. A successful reply confirms the integration is working. Chatbox chat window showing a successful response To add more models, go to the Chatbox settings page and add a new model entry using the current model ID you want. Chatbox settings page showing a new custom model added # Use ChatHub with CometAPI Source: https://apidoc.cometapi.com/integrations/chathub Use this guide to configure ChatHub with CometAPI by setting the base URL, API key, and model or provider options. [ChatHub](https://chathub.gg) is a browser extension that lets you talk to multiple AI models simultaneously. Add CometAPI as an OpenAI-compatible provider, then choose the model you want from the [Models page](/overview/models). ## Prerequisites * [ChatHub](https://chathub.gg) browser extension installed * A [CometAPI](https://www.cometapi.com) account with an active API key ## Setup Log in to the [CometAPI dashboard](https://www.cometapi.com/console). Click **Add API Key** and copy your key and base URL (`https://api.cometapi.com`). CometAPI dashboard — Add API Key CometAPI API key and base URL Open ChatHub **Settings** → **OpenAI**. Enter `https://api.cometapi.com` in the **API Host** field, paste your CometAPI key into **API Key**, and click **Save**. ChatHub OpenAI settings with CometAPI host filled in API key field filled in ChatHub settings Send a test message in ChatHub. A successful reply confirms the integration is working. ChatHub showing a successful response from CometAPI # Use Cherry Studio with CometAPI Source: https://apidoc.cometapi.com/integrations/cherrystudio Use this guide to configure Cherry Studio with CometAPI by setting the base URL, API key, and model or provider options. [CherryStudio](https://docs.cherry-ai.com/cherrystudio/download) is an AI desktop app supporting multiple model providers. Add CometAPI as a custom OpenAI-compatible provider to use any model on our platform. ## Prerequisites * [CherryStudio](https://docs.cherry-ai.com/cherrystudio/download) installed * A [CometAPI](https://www.cometapi.com) account with an active API key ## Setup Log in to the [CometAPI dashboard](https://www.cometapi.com/console). Click **Add API Key** and copy your key and base URL (`https://api.cometapi.com`). CometAPI dashboard — Add API Key CometAPI API key and base URL Open CherryStudio **Settings** → **Model Services**. Click **Add**, give the provider a name (e.g., `CometAPI`), select **OpenAI** as the provider type, and click **OK**. Enter `https://api.cometapi.com` in the **API Address** field and paste your key into the **Key** field. CherryStudio model services — Add provider dialog API address and key fields filled in for CometAPI Click **Add Model** and enter the current model ID you want to use. You can add multiple models. CherryStudio model list showing a custom model added Open a chat and send a test message. A successful response confirms the setup is working. CherryStudio chat showing a successful response To add more models, return to the provider settings and click **Add Model** again. CherryStudio settings showing another custom model added # Use Claude Code with CometAPI Source: https://apidoc.cometapi.com/integrations/claude-code Use this guide to configure Claude Code with CometAPI through Anthropic-compatible credentials, base URL settings, and Claude model IDs. Use this guide to connect [Claude Code](https://code.claude.com/docs/en/overview) to CometAPI. Official references: * [Claude Code Overview](https://code.claude.com/docs/en/overview) * [Claude Code Getting Started](https://code.claude.com/docs/en/getting-started) Model availability changes over time. For current Claude model IDs, check the [CometAPI Models page](/overview/models). ## Prerequisites * A CometAPI key from your [dashboard](https://www.cometapi.com) (starts with `sk-`) * Git installed * Supported OS: macOS, Linux, or Windows ## Install Claude Code ```bash theme={null} curl -fsSL https://claude.ai/install.sh | bash ``` ```bash theme={null} brew install --cask claude-code ``` PowerShell: ```powershell theme={null} irm https://claude.ai/install.ps1 | iex ``` CMD: ```batch theme={null} curl -fsSL https://claude.ai/install.cmd -o install.cmd && install.cmd && del install.cmd ``` Windows requires [Git for Windows](https://git-scm.com/downloads/win) installed first. ```bash theme={null} claude --version ``` ## Configure CometAPI endpoint Create or edit the settings file: * macOS / Linux: `~/.claude/settings.json` * Windows: `%USERPROFILE%\.claude\settings.json` ```json theme={null} { "env": { "ANTHROPIC_AUTH_TOKEN": "sk-your-cometapi-key", "ANTHROPIC_BASE_URL": "https://api.cometapi.com" } } ``` Replace `sk-your-cometapi-key` with your actual CometAPI key, then start Claude Code: ```bash theme={null} cd your-project claude ``` ## Troubleshooting 1. Restart your terminal completely by closing all windows and reopening it. 2. If it still does not work, create `~/.claude.json` and add: ```json theme={null} { "hasCompletedOnboarding": true } ``` 3. As a fallback, export environment variables directly: ```bash theme={null} # Add to ~/.zshrc (macOS) or ~/.bashrc (Linux) export ANTHROPIC_AUTH_TOKEN="sk-your-cometapi-key" export ANTHROPIC_BASE_URL="https://api.cometapi.com" ``` Check that `~/.claude/settings.json` exists and the JSON format is valid with no trailing commas and correct quotes. Validate at [jsonlint.com](https://jsonlint.com). Claude Code prioritizes cached official credentials. Run `/logout` inside Claude Code, close it, then restart. If it still fails, remove the cached auth file: ```bash theme={null} rm -rf ~/.config/claude-code/auth.json ``` Claude Code checks connectivity via Google. `offline` means Google is unreachable. This does not affect CometAPI usage. Claude Code's Fetch feature calls Anthropic's native service first, which requires direct internet access. A system-wide proxy may be needed. # Use Claude Desktop with CometAPI Source: https://apidoc.cometapi.com/integrations/claude-desktop Use this guide to configure Claude Desktop with CometAPI by setting the base URL, API key, and model or provider options. Use this guide to connect Claude Desktop Cowork on third-party inference to CometAPI. This configuration lets Claude Desktop send Claude Messages API requests to CometAPI from the Cowork, Projects, and supported desktop workflows. Official references: * [Claude Desktop installation and setup](https://claude.com/docs/cowork/3p/installation) * [Claude Desktop gateway configuration](https://claude.com/docs/cowork/3p/gateway) * [Claude Desktop configuration reference](https://claude.com/docs/cowork/3p/configuration) Claude Desktop third-party inference requires an Anthropic-compatible gateway. CometAPI supports Claude models through the [Anthropic Messages API](/api/text/anthropic-messages). Content that you send from Claude Desktop is processed by CometAPI and the selected model provider. Do not send confidential data unless your organization allows that workflow. ## Prerequisites * Claude Desktop installed from [claude.com/download](https://claude.com/download) * A Claude Desktop build that includes **Developer mode** and **Configure third-party inference** * A CometAPI account with an active API key * Access to Claude models in CometAPI * A network path that can reach `https://api.cometapi.com` Start from the Claude Desktop sign-in screen. If you already signed in with an Anthropic account, sign out before you configure third-party inference. ## Configuration Open Claude Desktop and stay on the sign-in screen. In the application menu, open **Help** → **Troubleshooting**, then select **Enable Developer Mode**. On Windows, the menu can be hard to reach before sign-in. Focus the email field, press `Tab` until the menu is focused, then press `Enter`. After developer mode is enabled, open **Developer** → **Configure third-party inference**. The configuration window opens with several sections in the left sidebar. Use the **Connection** section for the CometAPI settings. In the **Connection** section, enter the CometAPI values below: | Field | Value | | --------------------- | ---------------------------------------------- | | Inference provider | Gateway | | Gateway | Anthropic-compatible | | Gateway base URL | `https://api.cometapi.com` | | Gateway API key | Your CometAPI API key, such as `$COMETAPI_KEY` | | Gateway auth scheme | Bearer | | Gateway extra headers | Leave blank | Keep the base URL exactly as shown. Claude Desktop requires an HTTPS base URL. The following screenshot shows the Connection section filled with CometAPI values. Claude Desktop Connection settings with the CometAPI gateway base URL, API key field, and bearer auth scheme filled in In **Model list**, add these model IDs manually: | Model ID | Recommended use | | --------------------------- | ------------------------------------ | | `claude-opus-4-7` | Complex planning and agent tasks | | `claude-sonnet-4-6` | General desktop use | | `claude-haiku-4-5-20251001` | Lightweight prompts and quick drafts | The first model in the list becomes the default model. Put `claude-sonnet-4-6` first if you want a general-purpose default. Model availability can change. If a model does not appear in Claude Desktop after configuration, verify access on the [CometAPI Models page](/overview/models). The following screenshot shows the model list with the three Claude model IDs configured for CometAPI. Claude Desktop model list showing claude-opus-4-7, claude-sonnet-4-6, and claude-haiku-4-5-20251001 for CometAPI Click **Apply locally**. Claude Desktop writes the selected configuration to the local user profile and relaunches the app. If the app does not relaunch, quit Claude Desktop completely and open it again. On the sign-in screen, choose the option for Cowork on third-party inference. Open Cowork or Projects, select one of the configured Claude models, and send a short test prompt. A successful response confirms that Claude Desktop is using CometAPI for model calls. ## Verify the configuration Use a short prompt that does not require external tools: ```text theme={null} Reply with one sentence: Claude Desktop is connected through CometAPI. ``` If Claude Desktop returns a response, then the base URL, API key, and model list are configured correctly. The following screenshot shows a successful Cowork reply through CometAPI. Claude Desktop Cowork reply using CometAPI after the third-party inference setup To inspect the detected settings, open **Help** → **Troubleshooting** → **Copy Managed Configuration Report**. Secret values are redacted in the copied report. ## Troubleshooting Confirm that you selected **Help** → **Troubleshooting** → **Enable Developer Mode**. Then quit Claude Desktop completely and open it again. If the option is missing, install a Claude Desktop build that includes third-party inference configuration. Check these items: * **Inference provider** is set to **Gateway**. * **Gateway base URL** is `https://api.cometapi.com`. * **Gateway API key** contains your CometAPI API key with no extra spaces. * You clicked **Apply locally** and fully restarted Claude Desktop. Confirm that the base URL starts with `https://`. Claude Desktop does not accept plain HTTP gateway URLs. Also confirm that your CometAPI account has access to Claude models and that the API key has not been deleted or disabled. Reopen **Developer** → **Configure third-party inference** and check the **Model list** entries. Model IDs must match the IDs that CometAPI exposes. Add each model ID as a separate entry. Do not include quotes, commas, or extra spaces in the UI fields. Claude Desktop third-party inference expects an Anthropic-compatible gateway for this flow. Use `https://api.cometapi.com` and the Claude model IDs listed above. The Code tab uses the Claude Code engine inside Claude Desktop. Some desktop settings may not apply to Code sessions in the same way that they apply to Cowork. For standalone terminal usage, see the [Claude Code integration guide](/integrations/claude-code). # Use Cline with CometAPI Source: https://apidoc.cometapi.com/integrations/cline Use this guide to configure Cline with CometAPI by setting the base URL, API key, and model or provider options. [Cline](https://marketplace.visualstudio.com/items?itemName=saoudrizwan.claude-dev) is a VS Code extension that brings AI coding assistance directly into your editor. Configure it to use CometAPI as a custom OpenAI-compatible provider. ## Prerequisites * [Cline](https://marketplace.visualstudio.com/items?itemName=saoudrizwan.claude-dev) installed in VS Code * A [CometAPI](https://www.cometapi.com) account with an active API key ## Setup Search for **Cline** in the VS Code Extensions panel and install it. VS Code Extensions panel showing the Cline extension Log in to the [CometAPI dashboard](https://www.cometapi.com/console). Click **Add API Key** and copy your key and base URL (`https://api.cometapi.com`). CometAPI dashboard — Add API Key CometAPI API key and base URL Open Cline settings and select **OpenAI Compatible** as the provider. Enter `https://api.cometapi.com/v1` in the **Base URL** field, paste your key into **API Key**, and enter the model ID you want to use. Cline settings with OpenAI Compatible selected and CometAPI base URL entered Send a test prompt in Cline (e.g., ask it to generate a hello world function). A successful response confirms the integration is working. # Use Codex with CometAPI Source: https://apidoc.cometapi.com/integrations/codex Use this guide to configure Codex with CometAPI by editing the user-level config.toml provider settings. Use this guide to run [Codex](https://developers.openai.com/codex/quickstart) with CometAPI as a model provider. Official references: * [Codex quickstart](https://developers.openai.com/codex/quickstart) * [Codex config basics](https://developers.openai.com/codex/config-basic) * [Codex custom model providers](https://developers.openai.com/codex/config-advanced#custom-model-providers) * [Codex Authentication](https://developers.openai.com/codex/auth) * [Codex on Windows](https://developers.openai.com/codex/windows) ## Prerequisites | Requirement | Details | | ---------------- | -------------------------------------------------------------------------------------------------------------- | | OS | macOS, Linux, Windows native PowerShell, or Windows with WSL | | Git | 2.23+ recommended | | Codex | Install the Codex app or Codex CLI from the [Codex quickstart](https://developers.openai.com/codex/quickstart) | | CometAPI API key | Get one from the [CometAPI dashboard](https://www.cometapi.com/console/token) | | Model ID | Use a model ID from the [Models page](/overview/models) | ## Choose a setup path We provide two options to help you configure Codex quickly. Edit the user-level `~/.codex/config.toml` file directly. This is the most reliable path, especially for Windows and WSL users. Run the setup script as a shortcut. It writes the same provider configuration and stores the CometAPI API key for Codex. ## Configure Codex manually Codex reads personal provider defaults from the user-level `~/.codex/config.toml` file. Configure the CometAPI provider there, not in a project `.codex/config.toml` file. Codex ignores provider and provider-auth settings in project config files. The recommended setup uses a named `cometapi` provider and command-backed authentication. This keeps CometAPI separate from the built-in OpenAI provider, does not require shell environment inheritance, and does not replace `~/.codex/auth.json`. Store your CometAPI API key in a local key file: ```bash theme={null} mkdir -p "$HOME/.codex" printf "%s\n" "$COMETAPI_KEY" > "$HOME/.codex/cometapi_key" chmod 600 "$HOME/.codex/cometapi_key" ``` Add this configuration to `~/.codex/config.toml`: ```toml theme={null} model_provider = "cometapi" model = "your-model-id" [model_providers.cometapi] name = "CometAPI" base_url = "https://api.cometapi.com/v1" wire_api = "responses" [model_providers.cometapi.auth] command = "sh" args = ["-c", "cat \"$HOME/.codex/cometapi_key\""] ``` Store your CometAPI API key in the Windows Codex home directory: ```powershell theme={null} New-Item -ItemType Directory -Force "$HOME\.codex" | Out-Null Set-Content -NoNewline -Path "$HOME\.codex\cometapi_key" -Value $env:COMETAPI_KEY ``` Add this configuration to `$HOME\.codex\config.toml`: ```toml theme={null} model_provider = "cometapi" model = "your-model-id" [model_providers.cometapi] name = "CometAPI" base_url = "https://api.cometapi.com/v1" wire_api = "responses" [model_providers.cometapi.auth] command = "powershell.exe" args = [ "-NoProfile", "-Command", "$p=Join-Path $HOME '.codex/cometapi_key'; (Get-Content -Raw $p).Trim()", ] ``` Windows native Codex uses `$HOME\.codex`, usually `C:\Users\\.codex`. WSL uses the Linux distribution's `~/.codex`. Edit the directory that matches the environment where the Codex agent runs. ## Use environment variable authentication If you prefer to keep the CometAPI API key in an environment variable, use `env_key` instead of the `[model_providers.cometapi.auth]` block. Use this provider configuration only when `COMETAPI_KEY` is available in the environment that launches Codex: ```toml theme={null} model_provider = "cometapi" model = "your-model-id" [model_providers.cometapi] name = "CometAPI" base_url = "https://api.cometapi.com/v1" wire_api = "responses" env_key = "COMETAPI_KEY" ``` Do not combine `env_key` with `[model_providers.cometapi.auth]`. Codex supports one authentication method per custom provider. ## Run the setup script The setup script is optional. It writes the same `cometapi` provider configuration to `~/.codex/config.toml`, stores your CometAPI API key in `~/.codex/cometapi_key`, creates backups before file changes, and verifies the configuration with `codex exec` when the Codex CLI is available. For macOS, Linux, or WSL, run the interactive installer: ```bash theme={null} sh -c "$(curl -fsSL https://raw.githubusercontent.com/cometapi-dev/integrations/main/codex/setup.sh)" ``` For non-interactive setup, pass the API key explicitly: ```bash theme={null} curl -fsSL https://raw.githubusercontent.com/cometapi-dev/integrations/main/codex/setup.sh | sh -s -- --key "$COMETAPI_KEY" ``` For Windows native PowerShell, run the interactive installer: ```powershell theme={null} powershell -c "irm 'https://raw.githubusercontent.com/cometapi-dev/integrations/main/codex/setup.ps1' | iex" ``` For non-interactive Windows setup, pass the API key explicitly: ```powershell theme={null} powershell -c "& ([scriptblock]::Create((irm 'https://raw.githubusercontent.com/cometapi-dev/integrations/main/codex/setup.ps1'))) -Key $env:COMETAPI_KEY" ``` By default, the script does not replace `~/.codex/auth.json` and does not remove a ChatGPT login. Use `--force-auth-json` or `-ForceAuthJson` only if you want the script to manage Codex API-key login through `auth.json`. ## Choose or change a model ID Use a model ID from the [Models page](/overview/models). In manual configuration, change the `model` value in `~/.codex/config.toml`. For macOS, Linux, or WSL, pass `--model` when you run the setup script: ```bash theme={null} curl -fsSL https://raw.githubusercontent.com/cometapi-dev/integrations/main/codex/setup.sh | sh -s -- --key "$COMETAPI_KEY" --model your-model-id ``` For Windows native PowerShell, pass `-Model` when you run the setup script: ```powershell theme={null} powershell -c "& ([scriptblock]::Create((irm 'https://raw.githubusercontent.com/cometapi-dev/integrations/main/codex/setup.ps1'))) -Key $env:COMETAPI_KEY -Model 'your-model-id'" ``` The script uses `CODEX_HOME` when it is set. Otherwise it writes to the current environment's `~/.codex`. ## Verify the setup To verify the setup with the Codex CLI, run this read-only command from any local project: ```bash theme={null} codex exec --ephemeral --skip-git-repo-check --sandbox read-only --color never "Reply exactly with: COMETAPI_CODEX_OK" ``` If the Codex CLI is not available in `PATH`, open the Codex app and send a short prompt from a local project. ## Troubleshooting Confirm that `model_provider = "cometapi"` is in the user-level `~/.codex/config.toml` file. Update `~/.codex/cometapi_key`, or rerun the setup script with the updated `$COMETAPI_KEY` value. Use the manual Windows native PowerShell steps, then run the verification command. Use `--key "$COMETAPI_KEY"`, set `COMETAPI_KEY`, or run the interactive `sh -c "$(curl ...)"` command. Confirm that `base_url` is `https://api.cometapi.com/v1` in `~/.codex/config.toml`. Check the [Models page](/overview/models) for available model IDs. Edit `$HOME\.codex` for Windows native mode, or edit `~/.codex` inside WSL for WSL agent mode. Do not use `--force-auth-json` or `-ForceAuthJson` unless you want API-key login mode. # Use Continue with CometAPI Source: https://apidoc.cometapi.com/integrations/continue Use this guide to configure Continue with CometAPI by setting the base URL, API key, and model or provider options. [Continue](https://continue.dev) is an open-source VS Code extension for AI-powered coding assistance. It has a first-party CometAPI provider — no manual URL configuration needed. ## Prerequisites * [Continue](https://marketplace.visualstudio.com/items?itemName=Continue.continue) installed in VS Code * A [CometAPI](https://www.cometapi.com) account with an active API key ## Setup Search for **Continue** in the VS Code Extensions panel and install it. VS Code Extensions panel showing the Continue extension Log in to the [CometAPI dashboard](https://www.cometapi.com/console). Click **Add API Key** and copy your key. CometAPI dashboard — Add API Key CometAPI API key and base URL Open Continue **Settings** → **Models** → **+**. Search for `cometapi` in the provider list and select it. Paste your API key and choose the models you want to use. Continue settings — provider search with cometapi selected CometAPI provider configuration in Continue Model selection in Continue with CometAPI provider Open a file and send a test prompt via Continue. A successful response confirms the integration is working. Continue chat showing a successful response from CometAPI If CometAPI does not appear in the provider list, switch Continue to the **Preview** version and reopen the extension. Continue extension panel showing the Preview version toggle # Use Coze with CometAPI Source: https://apidoc.cometapi.com/integrations/coze Use this guide to configure Coze with CometAPI by setting the base URL, API key, and model or provider options. Coze is an AI agent and workflow builder. You can connect CometAPI to Coze in two ways: via the native **CometAPI plugin** (simplest) or via a generic **HTTP Request node** for maximum flexibility. ## Prerequisites * A CometAPI account with an active API key — [get yours here](https://www.cometapi.com/console/token) * A Coze account — [sign up here](https://www.coze.com) Log in to the [CometAPI console](https://www.cometapi.com/console/token). Click **Add API Key** and copy your CometAPI API key. CometAPI dashboard showing the Add API Key button CometAPI API key details with base URL 1. In Coze, click **Get Started** and create a new workflow. 2. In the workflow editor, click **Add Node → Plugins** and search for **CometAPI**. 3. Add the CometAPI plugin node to your workflow. Coze workflow editor showing plugin search CometAPI plugin appearing in search results CometAPI plugin node added to canvas Plugin node configuration panel 4. In the **API Key** field of the plugin node, paste your CometAPI API key. 5. Click **Test** to verify the connection, then **Publish**. Plugin node with API key filled in Successful test result for the CometAPI plugin 1. Create an agent in Coze, then in the agent's workflow add an **HTTP Request** node between the Start and End nodes. 2. Set the following: * **Method**: `POST` * **URL**: `https://api.cometapi.com/v1/chat/completions` * **Authentication Token**: paste your CometAPI API key, then click **Confirm** 3. Set the request body: ```json theme={null} { "model": "your-model-id", "messages": [ { "role": "user", "content": "{{block_output_100001.input}}" } ], "stream": false } ``` 4. In the End node, set the output to the HTTP request's response body. Replace `your-model-id` with a current model ID from the [CometAPI Models page](/overview/models). HTTP Request node with URL and auth token configured Request body JSON configured in the HTTP node End node with HTTP response body selected as output Coze workflow with all nodes connected Run a test message in the workflow (e.g. ask for the current time). A successful AI reply confirms the integration is working. Publish the workflow to make it live. Coze workflow showing a successful test response Published Coze agent responding correctly If the call fails, verify your API key and endpoint URL, or contact [CometAPI support](https://www.cometapi.com). The plugin method is recommended for most users — it handles authentication and response parsing automatically. Use the HTTP Request node when you need full control over request headers or want to call a non-chat endpoint. # Use CrewAI with CometAPI Source: https://apidoc.cometapi.com/integrations/crewai Use four CrewAI LLM transport configurations with CometAPI in one sequential multi-agent Crew. [CrewAI](https://docs.crewai.com/) is a Python framework for coordinating AI agents and tasks. This guide configures one sequential Crew to call CometAPI through four CrewAI transport configurations: OpenAI Chat Completions, OpenAI Responses, Anthropic Messages, and Gemini `generateContent`. ## Prerequisites * Python 3.10–3.13 * [`uv`](https://docs.astral.sh/uv/getting-started/installation/) * A CometAPI account with an active API key — [get yours in the dashboard](https://www.cometapi.com/console/token) * Four text model IDs for the transports shown below ## Configure the integration Create a new `uv` project and install CrewAI with its Anthropic and Google Gen AI extras: ```bash theme={null} uv init crewai-cometapi cd crewai-cometapi uv add 'crewai[anthropic,google-genai]' ``` Set the CometAPI API key and one model ID for each transport: ```bash theme={null} read -rsp "CometAPI API key: " COMETAPI_KEY printf '\n' export COMETAPI_KEY export COMETAPI_CHAT_MODEL_ID=your-model-id export COMETAPI_RESPONSES_MODEL_ID=your-model-id export COMETAPI_ANTHROPIC_MODEL_ID=your-model-id export COMETAPI_GEMINI_MODEL_ID=your-model-id ``` Replace every `your-model-id` value with a model ID from the [CometAPI Models page](/overview/models). The four values can be different. Assign each model ID to its corresponding transport. Save the following example as `crew.py`: ```python theme={null} import os from crewai import Agent, Crew, LLM, Process, Task api_key = os.environ["COMETAPI_KEY"] chat_llm = LLM( model=os.environ["COMETAPI_CHAT_MODEL_ID"], custom_openai=True, api="completions", base_url="https://api.cometapi.com/v1", api_key=api_key, max_tokens=512, max_retries=0, ) responses_llm = LLM( model=os.environ["COMETAPI_RESPONSES_MODEL_ID"], custom_openai=True, api="responses", base_url="https://api.cometapi.com/v1", api_key=api_key, max_completion_tokens=512, max_retries=0, ) anthropic_llm = LLM( model=f"anthropic/{os.environ['COMETAPI_ANTHROPIC_MODEL_ID']}", base_url="https://api.cometapi.com", api_key=api_key, max_tokens=512, max_retries=0, ) gemini_llm = LLM( model=f"gemini/{os.environ['COMETAPI_GEMINI_MODEL_ID']}", api_key=api_key, max_output_tokens=512, thinking_config={"thinking_budget": 0, "include_thoughts": False}, client_params={ "http_options": { "base_url": "https://api.cometapi.com", "api_version": "v1beta", } }, ) audience_agent = Agent( role="Audience researcher", goal="Define the audience for an API migration brief", backstory="You turn product goals into a precise audience statement.", llm=chat_llm, tools=[], allow_delegation=False, max_iter=1, max_retry_limit=0, verbose=False, ) requirements_agent = Agent( role="Requirements planner", goal="Turn an audience statement into implementation requirements", backstory="You write concise, testable requirements for API teams.", llm=responses_llm, tools=[], allow_delegation=False, max_iter=1, max_retry_limit=0, verbose=False, ) risk_agent = Agent( role="Risk reviewer", goal="Identify the most important migration risk", backstory="You review plans for practical delivery risks.", llm=anthropic_llm, tools=[], allow_delegation=False, max_iter=1, max_retry_limit=0, verbose=False, ) editor_agent = Agent( role="Release brief editor", goal="Combine research, requirements, and risk into one brief", backstory="You preserve source findings while producing clear summaries.", llm=gemini_llm, tools=[], allow_delegation=False, max_iter=1, max_retry_limit=0, verbose=False, ) audience_task = Task( description=( "Define one target audience for a team moving an existing OpenAI " "integration to a multi-provider API. Return only an Audience heading " "and one sentence of at most 20 words." ), expected_output="An Audience heading followed by one concise sentence.", agent=audience_agent, ) requirements_task = Task( description=( "Using the audience statement in your context, return only a " "Requirements heading and exactly two numbered requirements. Keep each " "requirement to at most 18 words." ), expected_output="A Requirements heading followed by two numbered items.", agent=requirements_agent, context=[audience_task], ) risk_task = Task( description=( "Using the audience and requirements in your context, return only a " "Risk heading, one risk sentence, and one mitigation sentence. Keep " "each sentence to at most 18 words." ), expected_output="A Risk heading with one risk and one mitigation.", agent=risk_agent, context=[audience_task, requirements_task], ) brief_task = Task( description=( "Create a release brief from all prior task outputs. Return only these " "sections: Audience with one sentence; Requirements with two numbered " "items; Risk with one risk and one mitigation. Keep the exact headings " "Audience, Requirements, and Risk." ), expected_output=( "A concise release brief with Audience, Requirements, and Risk headings." ), agent=editor_agent, context=[audience_task, requirements_task, risk_task], ) crew = Crew( agents=[ audience_agent, requirements_agent, risk_agent, editor_agent, ], tasks=[audience_task, requirements_task, risk_task, brief_task], process=Process.sequential, verbose=False, ) result = crew.kickoff() for index, task_output in enumerate(result.tasks_output, start=1): print(f"\n--- Task {index} ---\n{task_output.raw}") ``` The Agents have no tools, cannot delegate, and run one at a time. Every Task after the first declares its preceding Tasks in `context`, so CrewAI includes those prior outputs in the next Task. Run the example in the same shell session: ```bash theme={null} uv run python crew.py ``` The script prints all four Task outputs, including the final release brief. ## Route mapping | CrewAI configuration | CometAPI route | Base URL | | ------------------------------------------------------- | --------------------------------------------- | ----------------------------- | | `custom_openai=True`, `api="completions"` | `POST /v1/chat/completions` | `https://api.cometapi.com/v1` | | `custom_openai=True`, `api="responses"` | `POST /v1/responses` | `https://api.cometapi.com/v1` | | `anthropic/` model prefix | `POST /v1/messages` | `https://api.cometapi.com` | | `gemini/` model prefix and `client_params.http_options` | `POST /v1beta/models/{model}:generateContent` | `https://api.cometapi.com` | The two OpenAI configurations above need the `/v1` suffix in `base_url`. The Anthropic and Gemini configurations add their own versioned route, so their base URL is the CometAPI origin without `/v1`. ## Choose model IDs Use the [CometAPI Models page](/overview/models) to choose one text model ID for each transport. Store the model IDs in environment variables so you can change them without editing the Python file. Do not add a provider prefix to an environment variable. The example adds `anthropic/` and `gemini/` where CrewAI uses those prefixes for provider selection. ## Troubleshooting Run `uv add 'crewai[anthropic,google-genai]'` in the project. The base CrewAI package does not install both optional provider SDKs by default. Remove optional parameters that are not part of the selected model's interface. The example configures only the output token limit for Responses. Compare the `LLM` configuration with the route mapping table. In particular, use `custom_openai=True` with the correct `api` value, and keep the Gemini base URL inside `client_params.http_options`. ## Related resources * [CrewAI 1.15.12 LLM documentation](https://docs.crewai.com/v1.15.12/en/concepts/llms) * [CrewAI Agents](https://docs.crewai.com/v1.15.12/en/concepts/agents) * [CrewAI Tasks](https://docs.crewai.com/v1.15.12/en/concepts/tasks) * [CrewAI Crews](https://docs.crewai.com/v1.15.12/en/concepts/crews) * [CometAPI Chat Completions](/api/text/chat) * [CometAPI Responses](/api/text/responses) * [CometAPI Anthropic Messages](/api/text/anthropic-messages) * [CometAPI Gemini generateContent](/api/text/gemini-generating-content) # Connect Dify to CometAPI Source: https://apidoc.cometapi.com/integrations/dify Use this guide to connect Dify to CometAPI by setting the base URL, API key, and model or provider options. [Dify](https://dify.ai) is an open-source LLM application development platform. By connecting it to CometAPI, you can use current CometAPI model IDs inside Dify's workflow, chatbot, and agent builders. ## Prerequisites * A CometAPI account with an active API key — [sign in to get one](https://www.cometapi.com) * A Dify account — [cloud](https://cloud.dify.ai/signin) or self-hosted ## Method 1: CometAPI plugin (recommended) The easiest way to connect. Dify Marketplace provides an official CometAPI plugin that handles the integration automatically. Log in to the [CometAPI dashboard](https://www.cometapi.com/console). Click **Add API Key** and copy your key. CometAPI dashboard showing the Add API Key button and key list CometAPI API key details showing the base URL https://api.cometapi.com In Dify, go to **Plugins** → **Install Plugin** → **Marketplace**. Search for `cometapi` and install it. Dify plugin marketplace search results showing the CometAPI plugin CometAPI plugin installation confirmation dialog in Dify Go to **Settings** → **Model Provider** → **CometAPI** → **Open Settings**. Paste your CometAPI API key and click **Save**. Enter a model ID from the [CometAPI Models page](/overview/models) and click **Add**. Dify model provider settings showing the CometAPI configuration form Dify model list with CometAPI models successfully added Create a chatbot or workflow and select a CometAPI model. Send a test message — a successful response confirms the integration is working. Dify chat interface showing a successful response from a CometAPI model ## Method 2: OpenAI-compatible provider Use this method to add models not covered by the CometAPI plugin, such as Claude, Grok, or Gemini — or to use custom model names. Go to **Settings** → **Model Provider** → **OpenAI-API-compatible** → **Add Model**. Fill in the following fields: | Field | Value | | ------------ | ------------------------------------------- | | Model type | LLM | | Model name | Model ID from CometAPI (must match exactly) | | API key | Your CometAPI API key | | API base URL | `https://api.cometapi.com/v1` | Click **Save**. Dify OpenAI-compatible provider form with CometAPI values filled in Dify model list showing a newly saved CometAPI-compatible model entry For model identifiers, refer to the [CometAPI Models page](/overview/models). The model ID in Dify must exactly match the identifier used in CometAPI. ## Troubleshooting Confirm that the API key is correct and has available balance. Confirm that the model ID matches exactly what CometAPI expects. Confirm that the API base URL includes `/v1` for the OpenAI-compatible method. Visit the [CometAPI support page](https://www.cometapi.com/support/). # Use Eudic Translation with CometAPI Source: https://apidoc.cometapi.com/integrations/eudic-translation Use this guide to configure Eudic Translation with CometAPI by setting the base URL, API key, and model or provider options. [Eudic](https://www.eudic.net/v4/en/app/eudic) is a popular dictionary and translation app. Add CometAPI as a custom translation engine to power translations with any model on our platform. ## Prerequisites * [Eudic](https://www.eudic.net/v4/en/app/eudic) installed Eudic app interface * A [CometAPI](https://www.cometapi.com) account with an active API key ## Setup Log in to the [CometAPI dashboard](https://www.cometapi.com/console). Click **Add API Key** and copy your key and base URL (`https://api.cometapi.com`). CometAPI dashboard — Add API Key CometAPI API key and base URL Open Eudic → **Translation Engine** settings → **Add Translation Engine**. Find **Custom** in the dropdown, set it to **OpenAI**, and enter `https://api.cometapi.com/v1/chat/completions` in the **API Host** field. Paste your CometAPI key into the **API Key** field. Optionally enter a specific model ID. Click **Save**. Eudic add translation engine dialog API host and key fields filled in for CometAPI Model name field in Eudic translation engine settings Select text and trigger a translation. A successful result confirms the integration is working. # Use FastGPT with CometAPI Source: https://apidoc.cometapi.com/integrations/fastgpt Use this guide to configure FastGPT with CometAPI by setting the base URL, API key, and model or provider options. [FastGPT](https://cloud.tryfastgpt.ai/) is a knowledge-base-powered AI workflow platform. Configure a CometAPI key as an OpenAI-compatible third-party account to use it across all workflows. ## Prerequisites * A [FastGPT](https://cloud.tryfastgpt.ai/login) account * A [CometAPI](https://www.cometapi.com) account with an active API key ## Setup Log in to the [CometAPI dashboard](https://www.cometapi.com/console). Click **Add API Key** and copy your key and base URL (`https://api.cometapi.com`). CometAPI dashboard — Add API Key CometAPI API key and base URL In FastGPT, go to **Account Settings** → **Third-party Accounts** → **OpenAI Account**. Enter `https://api.cometapi.com/v1` in the **URL** field (include the `/v1` suffix). Paste your CometAPI key into **API Key** and click **Confirm**. FastGPT third-party accounts — OpenAI Account option URL and API key fields filled in for CometAPI in FastGPT Create a workflow with an LLM node and run it. A successful response confirms the setup is working. FastGPT workflow showing a successful response from CometAPI The URL must include the `/v1` suffix: `https://api.cometapi.com/v1`. Omitting it will cause connection failures. # Connect Flowise to CometAPI Source: https://apidoc.cometapi.com/integrations/flowiseai Use this guide to connect Flowise to CometAPI by setting the base URL, API key, and model or provider options. FlowiseAI is a low-code platform for building LLM applications visually. Use the native **ChatCometAPI** node to connect CometAPI to chatflows, Q\&A systems, and RAG workflows that call text chat models. This guide covers text chat and RAG workflows. It does not cover image generation workflows. ## Prerequisites * A CometAPI account with an active API key - [get yours here](https://www.cometapi.com/console/token) * A FlowiseAI account or self-hosted Flowise instance - [sign in to Flowise Cloud](https://cloud.flowiseai.com/chatflows) * A current text model ID from the [CometAPI Models page](/overview/models) * For RAG, a document source plus a Flowise-supported embeddings provider and vector store ## Configure ChatCometAPI Log in to the [CometAPI console](https://www.cometapi.com/console/token). Click **Add API Key** and copy your CometAPI API key. CometAPI dashboard showing the Add API Key button CometAPI API key details with base URL 1. In your FlowiseAI chatflow canvas, click **Add New**. FlowiseAI canvas with the Add New button 2. Search for **cometapi** and select the **ChatCometAPI** node. Node search showing ChatCometAPI result 3. Drag it onto the canvas. ChatCometAPI node placed on the canvas In the ChatCometAPI node, open **Connect Credential**, select **Create New**, paste your CometAPI API key, and save the credential. Credential dialog with API key entered Expand **Additional Parameters** on the ChatCometAPI node. If your Flowise build shows a **Base Path** field, set it to: ```text theme={null} https://api.cometapi.com/v1/ ``` If it exposes **Base Options** instead, add a `basePath` entry: ```json theme={null} { "basePath": "https://api.cometapi.com/v1/" } ``` Set **Model Name** to the exact text model ID you want to call, for example `your-model-id`, and adjust **Temperature** only if your workflow needs more or less variation. ## Create a basic chatflow Add a **Prompt Template** node and define the prompt your chatflow will send to the model. ```text theme={null} Question: {question} Answer clearly and concisely. ``` Prompt Template node with the example template Prompt Template node placed on canvas Add an **LLM Chain** node. Connect the **ChatCometAPI** node to the chain's **Language Model** input, then connect the **Prompt Template** node to the chain's **Prompt** input. LLM Chain node with Language Model and Prompt connected Save the chatflow, open the chat preview, and send a short test question. A healthy setup returns a normal text answer from the selected CometAPI model. Complete chatflow with all three nodes connected ## Switch model IDs To switch models, keep the same CometAPI credential and base path, then change only the ChatCometAPI model ID field. Use exact model IDs from the [CometAPI Models page](/overview/models). Avoid copying display names, provider names, or extra spaces. | Use case | Model ID value | | ------------------------- | ------------------------- | | General chat model family | `your-chat-model-id` | | Reasoning model family | `your-reasoning-model-id` | | Coding model family | `your-coding-model-id` | After changing the model ID, save the chatflow and run a short test prompt. If you maintain multiple production flows, duplicate the chatflow first and give each copy a name that reflects the model family. ## Configure retrieval-augmented generation Flowise RAG has two parts: first prepare and upsert documents in **Document Stores**, then connect the prepared retriever to a chatflow. ChatCometAPI is the chat model that writes the final answer; the Document Store still needs a Flowise-supported embeddings provider and vector store. In Flowise, open **Document Stores** and create a new store. Add a document loader, such as **File Loader**, **PDF Loader**, **Web Scraper**, or another loader that matches your source. Add a text splitter when the document is long enough to need chunking, then click **Process** to preview the generated chunks. Click **Upsert** or **Upsert All Chunks**. Select: * **Embeddings**: a Flowise embeddings node compatible with your data and vector store. * **Vector Store**: the vector database where Flowise should store document embeddings. * **Record Manager**: optional. Use it when you want repeat upserts to avoid duplicate records. Keep the embedding model dimension aligned with the vector store index dimension. After upsert finishes, use the Document Store's retrieval query test to confirm that relevant chunks are returned before building the chatflow. In a chatflow, add a **Document Store (Vector)** or **Document Store Retriever** node and select the processed Document Store. Set **Top K** to the number of chunks you want Flowise to retrieve for each question. Add **Conversational Retrieval QA Chain** and connect: * **Language Model** input from **ChatCometAPI**. * **Vector Store Retriever** input from the Document Store retriever. * **Memory** only if your chatflow needs conversation history. Enable **Return Source Documents** when you want the answer to include citations or retrieved source chunks. Save the flow and ask a question whose answer exists only in the uploaded document. ## Troubleshooting Confirm that your Flowise version includes the **ChatCometAPI** chat model integration. In older or customized Flowise deployments, update Flowise or check whether the integration has been disabled by the administrator. Set the CometAPI base path to `https://api.cometapi.com/v1/`. In some Flowise builds this is a **Base Path** field. In others, add `basePath` inside **Base Options**. Do not use `https://api.cometapi.com` for the ChatCometAPI chatflow, because the chat node calls OpenAI-compatible `/chat/completions` routes under `/v1`. Recopy the key from the [CometAPI console](https://www.cometapi.com/console/token), create a fresh Flowise credential, and make sure the chatflow uses that credential. If the same key works in direct API calls but fails in Flowise, check that Flowise is not still using an older credential attached to the node. Replace the model ID value in the ChatCometAPI node with an exact current text model ID from the [CometAPI Models page](/overview/models). The value should not include quotes, a provider prefix, a display label, or trailing spaces. ChatCometAPI is a chat model node for text workflows. Use it for chat, chains, agents, and RAG answer generation. Do not use this Flowise setup for image generation nodes or image-only workflows. First test the Document Store retrieval query before testing the full chatflow. If retrieval is weak, tune the text splitter, chunk size, chunk overlap, metadata filters, and **Top K**. If citations are missing, enable **Return Source Documents** on **Conversational Retrieval QA Chain**. Check that the embedding provider, vector store, and vector dimensions match. Flowise Cloud vector stores often require their own reachable service URL and credentials; a local-only vector store URL such as `localhost` will not be reachable from Flowise Cloud. Record Manager is optional, but if you enable it, configure its database connection separately. Lower retrieval **Top K**, reduce prompt size, use smaller chunks, or choose a faster model ID for the ChatCometAPI node. For rate limits, wait and retry with lower concurrency, then check account usage and limits in the CometAPI console. # Use Gemini CLI with CometAPI Source: https://apidoc.cometapi.com/integrations/gemini-cli Use this guide to configure Gemini CLI with CometAPI credentials, base URL settings, and Gemini model IDs. Use this guide to run [Gemini CLI](https://github.com/google-gemini/gemini-cli) with CometAPI as the API endpoint. Official references: * [Gemini CLI GitHub](https://github.com/google-gemini/gemini-cli) * [Gemini CLI Authentication](https://github.com/google-gemini/gemini-cli/blob/main/docs/get-started/authentication.mdx) Model availability changes over time. Check the [CometAPI Models page](/overview/models) for available Gemini models. ## Prerequisites | Requirement | Details | | ------------ | ---------------------------------------------------------------------------- | | Node.js | 22+ (LTS recommended) | | OS | macOS, Linux, or Windows | | CometAPI key | From your [CometAPI Dashboard](https://www.cometapi.com) (starts with `sk-`) | ## Setup ```bash theme={null} npm install -g @google/gemini-cli ``` Or via Homebrew (macOS / Linux): ```bash theme={null} brew install gemini-cli ``` Verify: ```bash theme={null} gemini --version ``` ```bash theme={null} export GEMINI_API_KEY="sk-your-cometapi-key" export GOOGLE_GEMINI_BASE_URL="https://api.cometapi.com" ``` Replace `sk-your-cometapi-key` with your actual CometAPI key. ```bash theme={null} cd your-project gemini ``` On first launch, you'll be prompted to choose a theme, confirm the safety notice, and trust the working directory. ## Persist environment variables To avoid re-exporting every session, add to your shell config: ```bash theme={null} # Add to ~/.zshrc (macOS) or ~/.bashrc (Linux) export GEMINI_API_KEY="sk-your-cometapi-key" export GOOGLE_GEMINI_BASE_URL="https://api.cometapi.com" ``` Restart your terminal for changes to take effect. ## Troubleshooting Verify `GEMINI_API_KEY` is set correctly. Run `echo $GEMINI_API_KEY` to check. Network restrictions may block the connection. Try a system-wide proxy. Gemini CLI requires Node.js 22+. Run `node --version` to check. Run `npm uninstall -g @google/gemini-cli`. # Use GPT Academic with CometAPI Source: https://apidoc.cometapi.com/integrations/gpt-academic-optimization Use this guide to configure GPT Academic with CometAPI by setting the base URL, API key, and model or provider options. [gpt\_academic](https://github.com/binary-husky/gpt_academic) is an open-source tool that enhances academic writing and code review using large language models. Connect it to CometAPI to use GPT, Claude, and other models in your research workflows. ## Prerequisites * [gpt\_academic](https://github.com/binary-husky/gpt_academic) installed and running * A [CometAPI](https://www.cometapi.com) account with an active API key ## Setup Log in to the [CometAPI dashboard](https://www.cometapi.com/console). Click **Add API Key** and copy your key and base URL (`https://api.cometapi.com`). CometAPI dashboard — Add API Key CometAPI API key and base URL Open `gpt_academic/config.py`. Set the API endpoint to `https://api.cometapi.com/v1/chat/completions` and paste your CometAPI key as the API key value. gpt_academic config.py — API URL and key fields Restart gpt\_academic and try a simple task. A successful response confirms CometAPI is connected. # Use gptme with CometAPI Source: https://apidoc.cometapi.com/integrations/gptme Use this guide to configure gptme with CometAPI by setting the base URL, API key, and model or provider options. [gptme](https://github.com/ErikBjare/gptme) is a terminal-based AI assistant. Configure it to use CometAPI by editing the `config.toml` file. ## Prerequisites * [gptme](https://github.com/ErikBjare/gptme) installed * A [CometAPI](https://www.cometapi.com) account with an active API key ## Setup Log in to the [CometAPI dashboard](https://www.cometapi.com/console). Click **Add API Key** and copy your key and base URL (`https://api.cometapi.com`). CometAPI dashboard — Add API Key CometAPI API key and base URL Open `~/.config/gptme/config.toml` (create it if it doesn’t exist). Set `url` to `https://api.cometapi.com/v1` and paste your CometAPI key as the API key. gptme config.toml — URL and API key fields Run `gptme` in your terminal and send a test prompt. A successful response confirms the integration is working. # Use Hermes Agent with CometAPI Source: https://apidoc.cometapi.com/integrations/hermes-agent Use this guide to connect Hermes Agent to CometAPI through OpenAI-compatible chat or Anthropic Messages settings. Use [CometAPI](https://www.cometapi.com) as the model provider for [Hermes Agent](https://hermes-agent.nousresearch.com/docs/). Hermes supports two CometAPI paths in this guide: a general OpenAI-compatible endpoint for most text models and a Claude route through Anthropic Messages. ## Prerequisites * Git * A CometAPI account with an active API key * A terminal on macOS, Linux, or WSL2 ## Installation Log in to the [CometAPI console](https://www.cometapi.com/console/token). Click **Add API Key** and copy your CometAPI API key. CometAPI dashboard showing the Add API Key button CometAPI API key details with the base URL shown The following command runs the official installer: ```bash theme={null} curl -fsSL https://raw.githubusercontent.com/NousResearch/hermes-agent/main/scripts/install.sh | bash ``` If the current shell does not see the `hermes` command yet, reload the shell configuration: ```bash theme={null} source ~/.zshrc # or source ~/.bashrc ``` Hermes stores config in `~/.hermes/`, links the `hermes` command in `~/.local/bin`, and may add `~/.local/bin` to your shell PATH. ## Configuration Choose the CometAPI route that matches the model family: | Model family | Hermes configuration | CometAPI route | | ----------------------------- | ------------------------------------------------------------------------------------------ | --------------------------- | | OpenAI-compatible text models | `model.provider: custom` with `base_url: https://api.cometapi.com/v1` | `/v1/chat/completions` | | Claude models | Named provider with `transport: anthropic_messages` | `/v1/messages` | | Gemini models in Hermes | Use the OpenAI-compatible configuration | `/v1/chat/completions` | | Direct Gemini API calls | Use the [Gemini `generateContent` API](/api/text/gemini-generating-content) outside Hermes | `/v1beta` `generateContent` | Do not configure Hermes with `https://api.cometapi.com/v1beta` as a custom Gemini-native provider. Use the OpenAI-compatible Hermes configuration for Gemini models. For direct Gemini API calls, use the [Gemini `generateContent` API](/api/text/gemini-generating-content). Open `~/.hermes/.env` and add the following values: ```dotenv theme={null} COMETAPI_KEY= OPENAI_API_KEY= ``` `COMETAPI_KEY` is used by the named Claude provider. `OPENAI_API_KEY` keeps Hermes's custom OpenAI-compatible endpoint fallback working. Use this route for most CometAPI text models, including Gemini models used from Hermes. Open `~/.hermes/config.yaml` and make sure the `model` section looks like this: ```yaml theme={null} model: provider: custom default: your-model-id base_url: https://api.cometapi.com/v1 ``` Replace `your-model-id` with a current text model ID from the [CometAPI Models page](https://www.cometapi.com/models/). Keep the API key in `~/.hermes/.env`. Do not hardcode secrets in `config.yaml`. This setup configures the main chat model. Hermes can use separate auxiliary models for tasks such as vision or web extraction. Use this route when you want Hermes to call Claude models through Anthropic Messages. Open `~/.hermes/config.yaml` and use a named provider: ```yaml theme={null} model: provider: cometapi-claude default: your-claude-model-id providers: cometapi-claude: base_url: https://api.cometapi.com key_env: COMETAPI_KEY transport: anthropic_messages default_model: your-claude-model-id ``` Replace `your-claude-model-id` with a current Claude model ID from the [CometAPI Models page](https://www.cometapi.com/models/). Keep `base_url` at `https://api.cometapi.com` for this route. Hermes uses the Anthropic Messages transport from the named provider. ## Verification The following command confirms that Hermes can read the config and the API key: ```bash theme={null} hermes config check ``` If `hermes config check` reports missing options after an update, run `hermes config migrate` and check again. The following command sends a real request through CometAPI: ```bash theme={null} hermes chat -Q --ignore-rules --max-turns 1 -q "Reply with CONNECTED only." ``` A successful setup returns `CONNECTED` and no auth or endpoint errors. When the Claude Messages configuration is active, this confirms that Hermes can use the `anthropic_messages` transport through CometAPI. ## Optional configuration If you are replacing an older Hermes install, use the built-in uninstaller first: ```bash theme={null} hermes uninstall ``` In the uninstaller, choose **Full uninstall** to remove the CLI, PATH entry, and `~/.hermes/` data. Then rerun the install step and continue with the same CometAPI configuration. If you prefer the interactive flow for the OpenAI-compatible route, run `hermes model` and choose **Custom endpoint**. Then enter the following values: * Base URL: `https://api.cometapi.com/v1` * API key: your CometAPI API key * Model: a current CometAPI text model ID This flow writes the OpenAI-compatible provider settings into `config.yaml`. For Claude Messages, edit `config.yaml` directly so the named provider keeps `transport: anthropic_messages`. # Use Immersive Translation with CometAPI Source: https://apidoc.cometapi.com/integrations/immersive-translation Use this guide to configure Immersive Translation with CometAPI by setting the base URL, API key, and model or provider options. [Immersive Translation](https://immersivetranslate.com/) is a browser extension for bilingual translation. Connect it to CometAPI to power translations with any model on our platform. ## Prerequisites * Immersive Translation browser extension installed — search for it in your browser’s extension store Browser extension store showing Immersive Translation Immersive Translation extension installation page * A [CometAPI](https://www.cometapi.com) account with an active API key ## Setup Log in to the [CometAPI dashboard](https://www.cometapi.com/console). Click **Add API Key** and copy your key and base URL (`https://api.cometapi.com`). CometAPI dashboard — Add API Key CometAPI API key and base URL Right-click the Immersive Translation extension icon → **Extension Settings** → **Translation Services**. Click **Add OpenAI Compatible Service**, enter `https://api.cometapi.com/v1/chat/completions` in the **API Address** field, and paste your key into **API Key**. Immersive Translation extension settings — add service dialog API address and key fields filled in for CometAPI Click **Test Service** in the settings panel. A successful verification confirms the integration is working. Immersive Translation service test showing a successful result You can also customize the model ID on the settings page by entering the model ID you want to use. # Integrate CometAPI with tools Source: https://apidoc.cometapi.com/integrations/index Use these guides to connect CometAPI to coding agents, chat clients, automation platforms, evaluation tools, and AI frameworks. CometAPI provides OpenAI, Anthropic (Claude), and Google (Gemini) compatible API endpoints. Any application that supports custom base URL and API key configuration for these providers can connect to CometAPI — no special SDK or adapter required. Use the integration cards below to open the setup guide for each tool. Most compatible tools need only these two values: * **Base URL**: `https://api.cometapi.com` * **API Key**: Your CometAPI key from the [dashboard](https://www.cometapi.com/console) ## Coding agents Use CometAPI as the model backend for your coding assistant. ## Agents Connect CometAPI to autonomous and semi-autonomous AI agent platforms. ## Chat clients Use CometAPI as a custom model provider in your preferred chat interface. ## Automation platforms Add AI capabilities to your workflows through visual automation builders. ## Observability and evaluation Use CometAPI in observability, evaluation, and red-team workflows. ## Frameworks Integrate CometAPI into your codebase through popular AI/ML SDKs. # Use IntelliJ Translation Plugin with CometAPI Source: https://apidoc.cometapi.com/integrations/intellij-translation-plugin Use this guide to configure IntelliJ Translation Plugin with CometAPI by setting the base URL, API key, and model or provider options. The [IntelliJ Translation Plugin](https://plugins.jetbrains.com/plugin/8579-translation) adds AI translation capabilities directly into JetBrains IDEs. Connect it to CometAPI to translate code and text without leaving your editor. ## Prerequisites * [IntelliJ IDEA](https://www.jetbrains.com/idea/) or another JetBrains IDE * Translation Plugin installed — search for **Translation** in the JetBrains Marketplace JetBrains Marketplace showing the Translation plugin * A [CometAPI](https://www.cometapi.com) account with an active API key ## Setup Log in to the [CometAPI dashboard](https://www.cometapi.com/console). Click **Add API Key** and copy your key. CometAPI dashboard — API keys section Add API Key dialog in CometAPI console CometAPI API key and base URL Click the Translation Plugin icon in the IDE toolbar → **Settings** → **Translation**. Select **OpenAI Translation** as the engine. In the settings panel on the right, enter `https://api.cometapi.com` in the **API Endpoint** field (the second field defaults to `/v1/chat/completions`). Paste your CometAPI key into **API Key** and click **Confirm**. CometAPI dashboard — Add API Key button and key list CometAPI API key details Click **Test Service** in the plugin settings. A successful verification confirms the setup is working. IntelliJ Translation Plugin test — successful result To add custom models, enter the current model ID in the plugin’s model configuration field. IntelliJ Translation Plugin model settings showing a custom model added # Use LangChain with CometAPI Source: https://apidoc.cometapi.com/integrations/langchain Use this guide to configure LangChain with CometAPI by setting the base URL, API key, and model or provider options. [LangChain](https://www.langchain.com/) is a popular framework for building LLM-powered applications. CometAPI is fully compatible with `langchain-openai` — just point it at our base URL. ## Prerequisites * Python 3.8+ and `langchain-openai` installed (`pip install langchain-openai`) * A [CometAPI](https://www.cometapi.com) account with an active API key ## Setup Log in to the [CometAPI dashboard](https://www.cometapi.com/console). Click **Add API Key** and copy your key and base URL (`https://api.cometapi.com`). CometAPI dashboard — Add API Key CometAPI API key and base URL Set your CometAPI key and base URL when initializing `ChatOpenAI`. **Option A — Environment variables (recommended)**: ```bash theme={null} export OPENAI_API_KEY=$COMETAPI_KEY export OPENAI_API_BASE=https://api.cometapi.com/v1 ``` **Option B — Inline configuration**: LangChain code showing ChatOpenAI initialized with CometAPI base URL and key Code example — ChatOpenAI initialization with CometAPI parameters Run a simple chain (e.g., a prompt asking for the current date). A successful response confirms CometAPI is connected. Use `base_url="https://api.cometapi.com/v1"` and `api_key=os.environ["COMETAPI_KEY"]` when initializing `ChatOpenAI` or `OpenAI` from `langchain-openai`. Any model ID from the [CometAPI model list](/overview/models) will work. # Connect Langflow to CometAPI Source: https://apidoc.cometapi.com/integrations/langflow Use this guide to connect Langflow to CometAPI by setting the base URL, API key, and model or provider options. [Langflow](https://www.langflow.org/) is a visual framework for building agent and RAG workflows. Langflow includes a CometAPI component that calls CometAPI language models through OpenAI-compatible endpoints. ## Prerequisites * Langflow Desktop, Langflow Cloud, or a self-hosted Langflow instance * A CometAPI account with an active API key — [get yours in the dashboard](https://www.cometapi.com/console/token) * A model ID from the [CometAPI Models page](/overview/models) ## Configure the integration In the Langflow canvas, open the component menu. Search for **CometAPI**, then add the CometAPI text generation component to your flow. Select the CometAPI component. In the component inspection panel, enter your CometAPI API key in the API key field. Set the model ID to a value from the [CometAPI Models page](/overview/models). If the component can fetch models after you enter the API key, select the model ID from the model menu. For a minimal test flow, add **Chat Input** and **Chat Output** components. Connect **Chat Input** to the CometAPI component input, then connect the CometAPI output to **Chat Output**. Open Playground and send a short message. A successful chat response confirms that Langflow is calling CometAPI. ## Use CometAPI inside larger flows Change the CometAPI component output type to **Language Model** when another Langflow component needs an LLM input. This is useful for Agent, Prompt Template, and Smart Transform flows. For direct chat, keep the default model response output and connect it to a Chat Output component. ## Run the CometAPI flow from Python After you test the flow in Playground, you can call the same Langflow flow from Python. The Python code calls your Langflow server. It does not send requests directly to CometAPI. Keep the CometAPI API key and model ID in the CometAPI component inside Langflow. The REST API example sends a chat input to a flow ID or endpoint name: ```python theme={null} import os import requests langflow_url = os.environ.get("LANGFLOW_URL", "http://localhost:7860") langflow_api_key = os.environ["LANGFLOW_API_KEY"] flow_id = os.environ["LANGFLOW_FLOW_ID"] response = requests.post( f"{langflow_url}/api/v1/run/{flow_id}", headers={ "x-api-key": langflow_api_key, "Content-Type": "application/json", }, json={ "input_value": "Hello from CometAPI", "input_type": "chat", "output_type": "chat", }, timeout=60, ) response.raise_for_status() print(response.json()) ``` For projects that use the Langflow Python SDK, install `langflow-sdk` and call the same flow through `Client.run()`: ```python theme={null} from langflow_sdk import Client client = Client("http://localhost:7860", api_key="") response = client.run("FLOW_ID", input_value="Hello from CometAPI") print(response.first_text_output()) ``` Replace `FLOW_ID` with the flow ID or endpoint name from Langflow. Replace `` with your Langflow API key. This value is different from your CometAPI API key. ## Troubleshooting Update Langflow to a version that includes the CometAPI bundle. If your deployment hides some components, check the bundle settings or search under language model components. Confirm that the CometAPI API key is valid and that the account has access to the selected model. You can also enter the model ID manually. Check that the model ID matches CometAPI exactly and that the flow input is connected to the CometAPI component input. ## Related resources * [Langflow CometAPI bundle](https://docs.langflow.org/bundles-cometapi) * [Langflow API flow trigger](https://docs.langflow.org/concepts-publish) * [langflow-sdk package](https://pypi.org/project/langflow-sdk/) * [CometAPI quick start](/overview/quick-start) * [CometAPI Models page](/overview/models) # Connect Langfuse to CometAPI Source: https://apidoc.cometapi.com/integrations/langfuse Use this guide to connect Langfuse to CometAPI by setting the base URL, API key, and model or provider options. [Langfuse](https://langfuse.com/) provides LLM observability, prompt management, playgrounds, and evaluation workflows. Configure a Langfuse LLM Connection with CometAPI when you want Langfuse Playground or LLM-as-a-Judge evaluations to call CometAPI models. ## Prerequisites * A Langfuse Cloud project or a self-hosted Langfuse instance * A CometAPI account with an active API key — [get yours in the dashboard](https://www.cometapi.com/console/token) * At least one CometAPI model ID selected from the [CometAPI Models page](/overview/models) ## Configure the integration In Langfuse, open **Project Settings** → **LLM Connections**. Start the flow for adding an LLM API key. Select **OpenAI** as the provider. Langfuse uses this adapter for model providers that support the OpenAI API schema. Configure the connection with these values: | Field | Value | | ---------------- | ----------------------------------------------------------------------- | | API key | Your CometAPI API key | | Base URL | `https://api.cometapi.com/v1` | | Custom model IDs | One or more model IDs from the [CometAPI Models page](/overview/models) | If Langfuse exposes the base URL field under **Advanced Settings**, expand that section before saving the connection. In Langfuse Playground, select the CometAPI LLM connection and one of the configured model IDs. Send a short prompt to confirm that Langfuse receives a response. ## Use CometAPI for LLM-as-a-Judge Langfuse LLM-as-a-Judge evaluators can use the same LLM connection. Select the CometAPI connection in the evaluator configuration, then choose a model ID that supports tool calling if your scoring prompt requires structured extraction. Use provider options only when the selected CometAPI model supports those request fields. For model discovery, use the [CometAPI Models page](/overview/models) or the `/v1/models` API. ## Troubleshooting Add the exact CometAPI model ID to the custom model IDs list in the LLM connection. Langfuse does not discover every model automatically for custom OpenAI-compatible providers. Use `https://api.cometapi.com/v1` as the base URL. Langfuse appends the OpenAI-compatible path for the selected adapter. Confirm that the selected model supports the request features used by the evaluator, such as tool calling or JSON output. ## Related resources * [Langfuse LLM Connections](https://langfuse.com/docs/administration/llm-connection) * [CometAPI quick start](/overview/quick-start) * [CometAPI Models page](/overview/models) # Use LibreChat with CometAPI Source: https://apidoc.cometapi.com/integrations/librechat Use this guide to configure LibreChat with CometAPI by setting the base URL, API key, and model or provider options. [LibreChat](https://www.librechat.ai/) is an open-source chat UI that supports multiple AI providers. Connect it to CometAPI by configuring it as an OpenAI-compatible endpoint. ## Prerequisites * LibreChat — [cloud](https://librechat-librechat.hf.space/), [self-hosted](https://github.com/danny-avila/LibreChat), or local * A [CometAPI](https://www.cometapi.com) account with an active API key ## Setup Log in to the [CometAPI dashboard](https://www.cometapi.com/console). Click **Add API Key** and copy your key and base URL (`https://api.cometapi.com`). CometAPI dashboard — Add API Key CometAPI API key and base URL In LibreChat, go to **Settings** → **OpenAI**. Enter `https://api.cometapi.com` in the **URL** field, paste your key into **API Key**, and click **Save**. LibreChat settings — OpenAI URL and key fields LibreChat chat interface after CometAPI has been configured Start a conversation in LibreChat. A successful reply confirms the integration is working. # Use LiteLLM with CometAPI Source: https://apidoc.cometapi.com/integrations/litellm Use this guide to configure LiteLLM with CometAPI by setting the base URL, API key, and model or provider options. LiteLLM provides a unified Python API for 100+ LLM providers. CometAPI is natively supported — use the `cometapi/` prefix to route requests through CometAPI's model catalog. ## Prerequisites * Python 3.6+ * A CometAPI account with an active API key — [get yours here](https://www.cometapi.com/console/token) ```bash theme={null} pip install litellm ``` Set the API key as an environment variable (recommended) or pass it inline: ```python theme={null} import os from litellm import completion # Recommended: environment variable os.environ["COMETAPI_KEY"] = "" # Alternative: pass inline api_key = "" ``` Use environment variables to avoid hardcoding sensitive credentials in your scripts. Use the `cometapi/` format to specify models. You can pass the key via environment variable or explicitly: ```python theme={null} messages = [{"content": "Hello, how are you?", "role": "user"}] # Method 1: environment variable (recommended) response = completion(model="cometapi/your-model-id", messages=messages) # Method 2: explicit API key response = completion(model="cometapi/your-model-id", messages=messages, api_key=api_key) print(response.choices[0].message.content) ``` Use `acompletion` with `stream=True` for non-blocking, real-time responses: ```python theme={null} from litellm import acompletion import asyncio, traceback async def stream_call(): try: response = await acompletion( model="cometapi/your-model-id", messages=[{"content": "Hello, how are you?", "role": "user"}], stream=True, ) async for chunk in response: print(chunk) except Exception: print(f"Error: {traceback.format_exc()}") asyncio.run(stream_call()) ``` * **Model format**: CometAPI models use the prefix `cometapi/`, e.g. `cometapi/your-model-id`. See the [CometAPI Models page](/overview/models) for available models. * **Fine-tuning responses**: LiteLLM supports `temperature`, `max_tokens`, and `top_p` — add them to any `completion()` call, e.g. `completion(..., temperature=0.7)`. * **Error handling**: Wrap calls in `try/except` to catch invalid key errors or network issues. * **Security**: Never commit API keys to version control. Use environment variables or a secrets manager. * **Rate limits**: Monitor usage in the [CometAPI console](https://www.cometapi.com/console). * **More docs**: [LiteLLM documentation](https://docs.litellm.ai/docs/) — [CometAPI quick start](/overview/quick-start) # Use LlamaIndex with CometAPI Source: https://apidoc.cometapi.com/integrations/llamaindex Use this guide to configure LlamaIndex with CometAPI by setting the base URL, API key, and model or provider options. LlamaIndex provides the `CometLLM` class as a first-class integration with CometAPI. Use it to power RAG pipelines, agents, and LLM chains with any model in CometAPI's catalog. ## Prerequisites * Python 3.8+ * A CometAPI account with an active API key — [get yours here](https://www.cometapi.com/console/token) ```bash theme={null} pip install llama-index-llms-cometapi llama-index ``` ```python theme={null} from llama_index.llms.cometapi import CometLLM import os os.environ["COMETAPI_KEY"] = "" api_key = os.getenv("COMETAPI_KEY") ``` Using environment variables is safer than hardcoding credentials in scripts. ```python theme={null} from llama_index.core.llms import ChatMessage llm = CometLLM( api_key=api_key, max_tokens=256, context_window=4096, model="your-model-id", ) # Chat call messages = [ ChatMessage(role="system", content="You are a helpful assistant"), ChatMessage(role="user", content="Say 'Hi' only!"), ] resp = llm.chat(messages) print(resp) # Completion call resp = llm.complete("Who is Kaiming He?") print(resp) ``` Use `stream_chat` or `stream_complete` for real-time chunked output: ```python theme={null} # Streaming chat message = ChatMessage(role="user", content="Tell me what ResNet is") for chunk in llm.stream_chat([message]): print(chunk.delta, end="") # Streaming completion for chunk in llm.stream_complete("Tell me about Large Language Models"): print(chunk.delta, end="") ``` * **Models**: See the [CometAPI Models page](/overview/models) for all available options. * **Using other models**: Initialize with a different current model ID, e.g. `CometLLM(api_key=api_key, model="your-model-id", max_tokens=1024)`. * **Fine-tuning**: Pass `temperature` and `max_tokens` directly to `CometLLM(...)`. * **Error handling**: Wrap calls in `try/except` to catch key errors or network issues. * **Security**: Never commit API keys to version control. Use environment variables. * **More docs**: [LlamaIndex documentation](https://docs.llamaindex.ai/) — [CometAPI quick start](/overview/quick-start) — [Colab example](https://colab.research.google.com/github/run-llama/llama_index/blob/main/docs/docs/examples/llm/cometapi.ipynb) # Use LobeChat with CometAPI Source: https://apidoc.cometapi.com/integrations/lobe-chat Use this guide to configure LobeChat with CometAPI by setting the base URL, API key, and model or provider options. [Lobe-Chat](https://chat-preview.lobehub.com/) is a feature-rich open-source AI chat application with built-in support for CometAPI — no manual URL configuration needed. ## Prerequisites * [Lobe-Chat](https://chat-preview.lobehub.com/) (cloud or self-hosted) * A [CometAPI](https://www.cometapi.com) account with an active API key ## Setup Log in to the [CometAPI dashboard](https://www.cometapi.com/console). Click **Add API Key** and copy your key. CometAPI dashboard — Add API Key CometAPI API key and base URL In Lobe-Chat, click your avatar → **Application Settings** → **Model Providers**. Select **CometAPI**, paste your API key, and toggle the provider on. Then select a model to enable it. Lobe-Chat application settings — model provider list CometAPI provider settings in Lobe-Chat with API key entered Start a chat and send a test message. A successful response confirms the integration is working. Lobe-Chat conversation showing a successful response from CometAPI Lobe-Chat model response panel # Connect Make to CometAPI Source: https://apidoc.cometapi.com/integrations/make Use this guide to connect Make to CometAPI by setting the base URL, API key, and model or provider options. Make (formerly Integromat) is a visual automation platform. Connect CometAPI to build AI-powered workflows across hundreds of apps — no code required. ## Prerequisites * A CometAPI account with an active API key — [get yours here](https://www.cometapi.com/console/token) * A Make account — [sign up here](https://www.make.com/en/register) Log in to the [CometAPI console](https://www.cometapi.com/console/token). Click **Add API Key** and copy your CometAPI API key. CometAPI dashboard showing the Add API Key button CometAPI API key details with base URL In Make, click **Create scenario**. In the scenario editor, click the **+** icon and search for **CometAPI**. Make scenario editor with the module search open Make search results showing the CometAPI module Select **Make an API Call** as the action. When prompted to add a connection, paste your CometAPI API key and click **Save**. Make connection dialog with API key field Fill in the module settings: * **URL**: `/v1/chat/completions` * **Method**: `POST` * **Body** (JSON): ```json theme={null} { "model": "your-model-id", "messages": [ { "role": "user", "content": "Hello!" } ], "stream": false } ``` Click **Save**. Replace `your-model-id` with a current model ID from the [CometAPI Models page](/overview/models). Make module with endpoint and JSON body configured Click **Run once** to execute the scenario. A successful AI response in the output confirms the integration is working. Make scenario output showing a successful CometAPI response Make scenario run history showing success If the call fails, verify your API key and endpoint URL, or contact [CometAPI support](https://www.cometapi.com). You can replace the `/v1/chat/completions` endpoint with any CometAPI endpoint — for example `/v1/images/generations` for image generation. Adjust the JSON body to match the target endpoint's parameters. # Connect n8n to CometAPI Source: https://apidoc.cometapi.com/integrations/n8n Use this guide to connect n8n to CometAPI by setting the base URL, API key, and model or provider options. [n8n](https://n8n.io/) is a workflow automation tool. Connect it to CometAPI by configuring OpenAI-compatible credentials — all CometAPI models work out of the box. ## Prerequisites * An [n8n](https://n8n.io/) account (cloud or self-hosted) * A [CometAPI](https://www.cometapi.com) account with an active API key For local/self-hosted n8n with the CometAPI community node, see the [n8n Local Deployment](/integrations/n8n-local-deployment) guide. ## Setup Log in to the [CometAPI dashboard](https://www.cometapi.com/console). Click **Add API Key** and copy your key and base URL (`https://api.cometapi.com`). CometAPI dashboard — Add API Key CometAPI API key and base URL In n8n, navigate to your project → **Credentials** → **Create Credential** → **OpenAI API**. Paste your CometAPI key into **API Key**, enter `https://api.cometapi.com/v1` in the **Base URL** field, and click **Save**. n8n Create Credential dialog with OpenAI API selected n8n OpenAI credential form with CometAPI key and base URL filled in n8n credential saved successfully Create a workflow with an OpenAI node using the saved credential and execute it. A successful response confirms the setup is working. n8n workflow showing a successful response from CometAPI # Run n8n locally with CometAPI Source: https://apidoc.cometapi.com/integrations/n8n-local-deployment Use this guide to run n8n locally with CometAPI by configuring local deployment settings, credentials, and model access. Deploy n8n on your own machine and connect it to CometAPI via the community node to run automated AI workflows locally. ## Prerequisites * Linux (Ubuntu/Debian/CentOS, etc.) or macOS * 2 GB+ RAM, 10 GB+ free disk space * Shell access with reach to the public npm registry * Node.js 18.x or 20.x LTS (see Step 1) * A CometAPI account with an active API key — [get yours here](https://www.cometapi.com/console/token) Log in to the [CometAPI console](https://www.cometapi.com/console/token). Click **Add API Key** and copy your CometAPI API key. CometAPI dashboard showing the Add API Key button CometAPI API key details with base URL n8n 1.x requires Node.js 18.x or 20.x. The recommended approach is [nvm](https://github.com/nvm-sh/nvm): ```bash theme={null} # Install nvm curl -o- https://raw.githubusercontent.com/nvm-sh/nvm/v0.39.7/install.sh | bash # Reload your shell profile source ~/.bashrc # or ~/.zshrc on macOS # Install and activate the LTS version nvm install --lts nvm use --lts # Verify node -v npm -v ``` If you see `n8n: command not found` later, restart the terminal or ensure the nvm-managed npm global bin directory is on your `PATH`. ```bash theme={null} npm install -g n8n n8n -v # verify the installed version n8n start # runs on http://localhost:5678/ ``` If port 5678 is already in use: ```bash theme={null} export N8N_PORT=5679 n8n start ``` To keep n8n running after closing the terminal: ```bash theme={null} npm install -g pm2 pm2 start "n8n" --name n8n pm2 save pm2 status ``` Terminal showing n8n starting successfully n8n startup logs in the terminal Open [http://localhost:5678/](http://localhost:5678/) in your browser. On first run, the setup wizard asks you to create an **Owner** account (email + password). Complete this and sign in. n8n first-run setup wizard asking for Owner account details 1. Go to **Settings** (bottom-left) → **Community nodes** 2. Click **Install a community node** 3. Enter the package name: `@cometapi-dev/n8n-nodes-cometapi` 4. Check the risk acknowledgment box and click **Install** After installation you can search for **CometAPI** in the node panel. n8n Settings panel showing the Community nodes section Install dialog with the CometAPI package name entered If the Community Nodes section is missing: make sure you are signed in as the **Owner** account, and check **Settings → Security** to confirm community node installation is enabled. 1. Click **+ New** at the top to create a workflow. 2. Click **+** on the canvas and search for **CometAPI** to add the node. n8n workflow canvas with the CometAPI node search open CometAPI node added to the n8n canvas 3. Add a **Manual Trigger** node and connect it to the CometAPI node. 4. In the CometAPI node, under **Credential to connect with**, choose **Create new**. Paste your CometAPI API key into **CometAPI Key** and click **Save**. The Base URL defaults to `https://api.cometapi.com` and typically needs no change. CometAPI credential dialog with API key entered 5. Configure the node: * **Model**: enter the current model ID you want to use * **Messages**: set Role to `user`, Content to your test prompt (e.g. `Hello`) * Optional: add a `system` message, set **Max Tokens**, **Temperature**, etc. 6. Click **Execute step** to run the node. The **Output** panel shows the JSON response. n8n output panel showing a successful CometAPI JSON response * **`node-gyp` or native build errors** — install build tools: `sudo apt install build-essential python3` (Debian/Ubuntu) or Xcode Command Line Tools (macOS). * **npm permission errors (EACCES)** — use nvm for a user-level Node.js install; no `sudo` needed. * **Port conflict (`localhost:5678` unavailable)** — set `N8N_PORT=5679` (or another free port) before running `n8n start`. * **Community Nodes section missing** — sign in as the **Owner** account and check **Settings → Security**. * **npm install fails on corporate networks** — configure a proxy: `npm config set proxy http://user:pass@host:port` * **CometAPI node returns 401/403** — verify your API key and that the model is accessible on your CometAPI plan. * **Empty responses or token limit errors** — increase **Max Tokens**; adjust **Temperature** and **Top P** as needed. * **n8n stops when terminal closes** — use pm2: `pm2 start "n8n" --name n8n && pm2 save`. # Use NextChat with CometAPI Source: https://apidoc.cometapi.com/integrations/next-chat Use this guide to configure NextChat with CometAPI by setting the base URL, API key, and model or provider options. [NextChat](https://nextchat.club/) (formerly ChatGPT Next Web) is a one-click deployable AI chat app. Connect it to CometAPI using the OpenAI-compatible API settings. ## Prerequisites * [NextChat](https://nextchat.club/) (web, desktop, or self-hosted) * A [CometAPI](https://www.cometapi.com) account with an active API key ## Setup Log in to the [CometAPI dashboard](https://www.cometapi.com/console). Click **Add API Key** and copy your key and base URL (`https://api.cometapi.com`). CometAPI dashboard — Add API Key CometAPI API key and base URL Open NextChat **Settings** → **Custom Interface**. Select **OpenAI API**, enter `https://api.cometapi.com` in the **Interface Address** field, paste your key into **API Key**, and click **Save**. NextChat settings — custom interface and OpenAI API options Send a test message. A successful reply confirms the integration is working. To add custom models, go to **Settings** → **Custom Model Names** and enter entries in this format: ``` +your-model-id@OpenAI ``` Format: `+` adds a model, the name before `@` is the model ID, and `@OpenAI` means it uses OpenAI format. Separate multiple entries with commas. # Use Obsidian Text Generator with CometAPI Source: https://apidoc.cometapi.com/integrations/obsidian-s-text-generator-plugin Use this guide to configure Obsidian Text Generator with CometAPI by setting the base URL, API key, and model or provider options. [Text Generator](https://text-gen.com/) is an Obsidian plugin for AI-assisted writing. Connect it to CometAPI using the OpenAI Chat settings to access any supported model. ## Prerequisites * [Obsidian](https://obsidian.md/) with the Text Generator plugin installed — search for it in **Settings** → **Community Plugins** Text Generator plugin in the Obsidian plugin marketplace * A [CometAPI](https://www.cometapi.com) account with an active API key ## Setup Log in to the [CometAPI dashboard](https://www.cometapi.com/console). Click **Add API Key** and copy your key and base URL (`https://api.cometapi.com`). CometAPI dashboard — Add API Key CometAPI API key and base URL Open the Text Generator plugin settings. Select **OpenAI Chat** as the AI provider, enter `https://api.cometapi.com/v1` in the **API Address** field, and paste your CometAPI key into the **Key** field. Select a model and click **Save**. Text Generator settings — OpenAI Chat selected with CometAPI URL and key Open Obsidian and trigger a text generation prompt. A successful response confirms the integration is working. # Use Open WebUI with CometAPI Source: https://apidoc.cometapi.com/integrations/open-webui Use this guide to configure Open WebUI with CometAPI by setting the base URL, API key, and model or provider options. [Open WebUI](https://openwebui.com/) is a self-hosted web interface for AI models. Configure it to use CometAPI as an external OpenAI-compatible connection. ## Prerequisites * [Open WebUI](https://openwebui.com/) running (self-hosted or via the demo at [open.zetatechs.online](https://openwebui.com/)) * A [CometAPI](https://www.cometapi.com) account with an active API key ## Setup Log in to the [CometAPI dashboard](https://www.cometapi.com/console). Click **Add API Key** and copy your key and base URL (`https://api.cometapi.com`). CometAPI dashboard — Add API Key CometAPI API key and base URL In Open WebUI, go to **Admin Panel** → **Settings** → **External Connections**. Enable **External Link OpenAI API**, enter `https://api.cometapi.com/v1` in the **API Address** field, paste your key into the **Key** field, and click **Save**. Open WebUI external connections settings with CometAPI URL entered Open WebUI settings saved with CometAPI connection active Start a chat and send a test message. A successful reply confirms the integration is working. # Use NextAI Translator with CometAPI Source: https://apidoc.cometapi.com/integrations/openai-translator Use this guide to configure NextAI Translator with CometAPI by setting the base URL, API key, and model or provider options. [OpenAI Translator](https://github.com/openai-translator/openai-translator) is a cross-platform translation tool. Configure it to use CometAPI’s OpenAI-compatible endpoint to power translations with any supported model. ## Prerequisites * [OpenAI Translator](https://github.com/openai-translator/openai-translator/releases) installed * A [CometAPI](https://www.cometapi.com) account with an active API key ## Setup Log in to the [CometAPI dashboard](https://www.cometapi.com/console). Click **Add API Key** and copy your key and base URL (`https://api.cometapi.com`). CometAPI dashboard — Add API Key CometAPI API key and base URL Open OpenAI Translator. The general settings page appears on first launch. Select **OpenAI** as the model provider, enter `https://api.cometapi.com` in the **URL** field, and paste your key into **API Key**. OpenAI Translator settings — URL and API key fields Select some text and trigger a translation. A successful result confirms the integration is working. To use a custom model, check **No model API support**, select **Custom** from the model dropdown, and type the current model ID manually. OpenAI Translator — custom model ID option # Use OpenClaw with CometAPI Source: https://apidoc.cometapi.com/integrations/openclaw Use this guide to configure OpenClaw with CometAPI by setting the base URL, API key, and model or provider options. Use [CometAPI](https://www.cometapi.com) as the model provider for [OpenClaw](https://openclaw.ai) — 500+ models in one API. ## Prerequisites * Node.js ≥ 22 — recommended via [nvm](https://github.com/nvm-sh/nvm) * A CometAPI account with an active API key — [get yours here](https://www.cometapi.com/console/token) ## Installation Log in to the [CometAPI console](https://www.cometapi.com/console/token). Click **Add API Key** and copy your CometAPI API key. CometAPI dashboard showing the Add API Key button CometAPI API key details with base URL **Recommended** — use the official installer: ```bash theme={null} curl -fsSL https://openclaw.ai/install.sh | bash ``` Or install via npm: ```bash theme={null} npm install -g openclaw@latest ``` Then run the setup wizard once: ```bash theme={null} openclaw onboard --install-daemon ``` During onboarding, choose **Skip** in the Model/Auth step if you want to configure CometAPI manually. After onboarding, confirm the gateway is running: ```bash theme={null} openclaw gateway status openclaw dashboard ``` ## Configuration Write your key to `~/.openclaw/.env` so it is available to the daemon without being hardcoded in config files: ```bash theme={null} printf 'COMETAPI_KEY=%s\n' "$COMETAPI_KEY" >> ~/.openclaw/.env chmod 600 ~/.openclaw/.env ``` If you already inject `COMETAPI_KEY` through your shell, service manager, or a secrets workflow, skip this step — the config below uses `$\{COMETAPI_KEY\}` regardless of how the variable is set. CometAPI supports **four API formats**. Add one or more provider blocks to `~/.openclaw/openclaw.json`: | Provider | API Format | Endpoint called | Base URL | | --------------------------- | ---------------------- | --------------------------- | --------------------------------- | | `cometapi-openai` | `openai-completions` | `POST /v1/chat/completions` | `https://api.cometapi.com/v1` | | `cometapi-openai-responses` | `openai-responses` | `POST /v1/responses` | `https://api.cometapi.com/v1` | | `cometapi-claude` | `anthropic-messages` | `POST /messages` | `https://api.cometapi.com` | | `cometapi-google` | `google-generative-ai` | `POST /v1beta/...` | `https://api.cometapi.com/v1beta` | ```json theme={null} { "agents": { "defaults": { "model": { "primary": "cometapi-claude/your-claude-model-id" } } }, "models": { "mode": "merge", "providers": { "cometapi-openai": { "baseUrl": "https://api.cometapi.com/v1", "apiKey": "${COMETAPI_KEY}", "api": "openai-completions", "models": [{ "id": "your-chat-model-id", "name": "OpenAI-compatible text model" }] }, "cometapi-openai-responses": { "baseUrl": "https://api.cometapi.com/v1", "apiKey": "${COMETAPI_KEY}", "api": "openai-responses", "models": [{ "id": "your-responses-model-id", "name": "Responses API model" }] }, "cometapi-claude": { "baseUrl": "https://api.cometapi.com", "apiKey": "${COMETAPI_KEY}", "api": "anthropic-messages", "models": [{ "id": "your-claude-model-id", "name": "Claude family model" }] }, "cometapi-google": { "baseUrl": "https://api.cometapi.com/v1beta", "apiKey": "${COMETAPI_KEY}", "api": "google-generative-ai", "models": [{ "id": "your-gemini-model-id", "name": "Gemini family model" }] } } } } ``` You can keep only the providers you need, or keep all four to route between formats using `provider/model` references. Replace each `your-...-model-id` placeholder with a current model ID from the [CometAPI Models page](https://www.cometapi.com/models/) that matches the provider block. Use `cometapi-openai-responses` (`api: "openai-responses"`) for models that require the OpenAI Responses API. Use `cometapi-openai` (`api: "openai-completions"`) for models on the classic Chat Completions path. Both share the same `baseUrl` (`https://api.cometapi.com/v1`); the only difference is which downstream endpoint OpenClaw calls. The `auth-profiles.json` file is **not required** for this setup. Provider keys are resolved from `models.providers.*.apiKey` via the `$\{COMETAPI_KEY\}` env var. `auth-profiles.json` is only needed if you want per-profile credential rotation across multiple keys. ## Verification Restart the gateway after adding `.env` or changing provider config: ```bash theme={null} openclaw gateway restart ``` Then run diagnostics: ```bash theme={null} openclaw models status openclaw models list --provider cometapi-claude openclaw doctor ``` A successful setup looks like: * `openclaw models status` resolves the primary model to `cometapi-claude/your-claude-model-id` with no missing-auth warnings for CometAPI providers * `openclaw models list --provider cometapi-claude` lists your configured models * `openclaw doctor` reports no config or auth errors for CometAPI providers OpenClaw models status showing CometAPI providers authenticated ## Switch models ```bash theme={null} # Set the default model in config openclaw models set cometapi-claude/your-claude-model-id # Switch for the current chat session /model cometapi-openai/your-chat-model-id /model cometapi-openai-responses/your-responses-model-id /model cometapi-claude/your-claude-model-id /model cometapi-google/your-gemini-model-id ``` ## Troubleshooting If you are fixing a broken older setup, stop the gateway, remove `~/.openclaw`, then rerun onboarding before applying the CometAPI config: ```bash theme={null} openclaw gateway stop rm -rf ~/.openclaw openclaw onboard --install-daemon ``` This removes all local config, sessions, logs, auth state, and workspaces. Then follow Steps 3–5 again. # Use OpenCode with CometAPI Source: https://apidoc.cometapi.com/integrations/opencode Use this guide to configure four CometAPI API formats as custom providers in OpenCode. Use this guide to run [OpenCode](https://opencode.ai/docs/) with CometAPI. The configuration exposes four API formats through separate custom providers. This configuration was tested with OpenCode 1.18.16. Official references: * [OpenCode installation](https://opencode.ai/docs/#install) * [OpenCode configuration](https://opencode.ai/docs/config/) * [OpenCode custom providers](https://opencode.ai/docs/providers/#custom-provider) * [OpenCode model selection](https://opencode.ai/docs/models/) * [OpenCode permissions](https://opencode.ai/docs/permissions/) Replace each `your-model-id` value with a model ID from the [CometAPI Models page](/overview/models). Choose a model that accepts the API format of the surrounding provider entry. ## Prerequisites * Node.js and npm, or another installation method from the OpenCode guide * A CometAPI account with an active API key from the [dashboard](https://www.cometapi.com/console/token) * One or more model IDs from the [CometAPI Models page](/overview/models) ## Understand the API formats Each provider ID selects one SDK adapter and one API format. | Provider ID | OpenCode adapter | Base URL | API format | | -------------------- | --------------------------- | --------------------------------- | ---------------------- | | `cometapi-chat` | `@ai-sdk/openai-compatible` | `https://api.cometapi.com/v1` | Chat Completions | | `cometapi-responses` | `@ai-sdk/openai` | `https://api.cometapi.com/v1` | Responses | | `cometapi-messages` | `@ai-sdk/anthropic` | `https://api.cometapi.com/v1` | Anthropic Messages | | `cometapi-gemini` | `@ai-sdk/google` | `https://api.cometapi.com/v1beta` | Gemini generateContent | This guide verifies the Gemini streaming operation used during a normal OpenCode agent turn. The Google adapter appends `:streamGenerateContent?alt=sse` to the model path. Do not add `/chat/completions`, `/responses`, `/messages`, or a Gemini model path to `baseURL`. Each adapter appends its required operation path. ## Understand runtime permissions OpenCode runs with the permissions of the process that launches it. Start OpenCode in the intended project directory and keep a rollback path such as git. Use a container or sandbox when you need stronger filesystem, process, network, or API key boundaries. ## Configure OpenCode Install OpenCode with the official npm package: ```bash theme={null} npm install -g opencode-ai ``` Confirm that the CLI is available: ```bash theme={null} opencode --version ``` See the [OpenCode installation guide](https://opencode.ai/docs/#install) for Homebrew, Windows, Docker, and other installation methods. Store your CometAPI API key in the `COMETAPI_KEY` environment variable. Read the API key without displaying it in the terminal: ```bash theme={null} read -rsp "CometAPI API key: " COMETAPI_KEY printf '\n' export COMETAPI_KEY ``` Read the API key into the current PowerShell session: ```powershell theme={null} $secureKey = Read-Host "CometAPI API key" -AsSecureString $env:COMETAPI_KEY = [System.Net.NetworkCredential]::new( "", $secureKey ).Password ``` Set the variable in every shell session that launches OpenCode. Do not commit API keys to version control. Use one of these supported locations: * Global configuration: `~/.config/opencode/opencode.json` * Project configuration: `opencode.json` in the project root OpenCode merges configuration files. A project configuration overrides conflicting values from the global configuration. Use the global file when you want the providers in every project. Use the project file when a repository needs its own model entries. Create the selected configuration file. If the file already contains a `provider` object, merge these four entries into that object: ```json theme={null} { "$schema": "https://opencode.ai/config.json", "provider": { "cometapi-chat": { "npm": "@ai-sdk/openai-compatible", "name": "CometAPI Chat Completions", "options": { "baseURL": "https://api.cometapi.com/v1", "apiKey": "{env:COMETAPI_KEY}" }, "models": { "your-model-id": { "name": "CometAPI Chat model" } } }, "cometapi-responses": { "npm": "@ai-sdk/openai", "name": "CometAPI Responses", "options": { "baseURL": "https://api.cometapi.com/v1", "apiKey": "{env:COMETAPI_KEY}" }, "models": { "your-model-id": { "name": "CometAPI Responses model" } } }, "cometapi-messages": { "npm": "@ai-sdk/anthropic", "name": "CometAPI Anthropic Messages", "options": { "baseURL": "https://api.cometapi.com/v1", "apiKey": "{env:COMETAPI_KEY}" }, "models": { "your-model-id": { "name": "CometAPI Messages model" } } }, "cometapi-gemini": { "npm": "@ai-sdk/google", "name": "CometAPI Gemini", "options": { "baseURL": "https://api.cometapi.com/v1beta", "apiKey": "{env:COMETAPI_KEY}" }, "models": { "your-model-id": { "name": "CometAPI Gemini model" } } } } } ``` Replace each `your-model-id` key independently. The four entries can use different model IDs. The configuration does not set a top-level `model`. This lets you choose the required API format and model through `/models`. Do not use `/connect` for this configuration. The `apiKey` fields read `COMETAPI_KEY` from the environment. An unset variable resolves to an empty value instead of a stored `/connect` API key. Start OpenCode in the project that you want it to access: ```bash theme={null} opencode ``` Run `/models`, then select a `provider/model` entry. In the four verification runs for this guide, each model turn used the selected entry's matching API format. No cross-format request fan-out or automatic API format negotiation was observed. To verify Chat Completions from the command line, run: ```bash theme={null} opencode run \ --model cometapi-chat/your-model-id \ "Reply exactly with: COMETAPI_CHAT_OK" ``` To verify Responses from the command line, run: ```bash theme={null} opencode run \ --model cometapi-responses/your-model-id \ "Reply exactly with: COMETAPI_RESPONSES_OK" ``` To verify Anthropic Messages from the command line, run: ```bash theme={null} opencode run \ --model cometapi-messages/your-model-id \ "Reply exactly with: COMETAPI_MESSAGES_OK" ``` To verify Gemini generateContent from the command line, run: ```bash theme={null} opencode run \ --model cometapi-gemini/your-model-id \ "Reply exactly with: COMETAPI_GEMINI_OK" ``` ## Troubleshooting Confirm that the configuration is valid JSON. Each custom entry must be inside the top-level `provider` object, and each model ID must be inside the matching `models` object. Restart OpenCode, then open `/models` again. Confirm that `COMETAPI_KEY` is set in the shell that launches OpenCode. An unset `{env:COMETAPI_KEY}` reference becomes an empty value. Open a new shell after changing a shell profile. Check the [CometAPI Models page](/overview/models), then replace the model ID inside the selected provider entry. Confirm that the model accepts that provider's API format. Keep `baseURL` at `/v1` for Chat Completions, Responses, and Messages. Use `/v1beta` for Gemini. Do not include an operation path in `baseURL`. Use a model ID that accepts the selected provider's API format. Do not assume that one model ID accepts all four formats. OpenCode merges global and project configuration. Rename the project provider ID or remove its conflicting values when you want the global provider entry to remain unchanged. OpenCode uses the permissions of the process that launched it. Run OpenCode in a container or sandbox when you need stronger access boundaries. ## Related resources * [CometAPI quick start](/overview/quick-start) * [CometAPI Models page](/overview/models) * [OpenCode custom providers](https://opencode.ai/docs/providers/#custom-provider) * [OpenCode configuration](https://opencode.ai/docs/config/) * [OpenCode model selection](https://opencode.ai/docs/models/) # Use OpenManus with CometAPI Source: https://apidoc.cometapi.com/integrations/openmanus Use this guide to configure OpenManus with CometAPI by setting the base URL, API key, and model or provider options. [OpenManus](https://github.com/mannaandpoem/OpenManus) is an open-source agentic AI framework. Connect it to CometAPI by editing the `config.toml` file. ## Prerequisites * [OpenManus](https://github.com/mannaandpoem/OpenManus) deployed and running * A [CometAPI](https://www.cometapi.com) account with an active API key ## Setup Log in to the [CometAPI dashboard](https://www.cometapi.com/console). Click **Add API Key** and copy your key and base URL (`https://api.cometapi.com`). CometAPI dashboard — Add API Key CometAPI API key and base URL In the `config/` directory, copy the example config file to `config.toml`. Set `base_url` to `https://api.cometapi.com/v1` and paste your CometAPI key as `api_key`. OpenManus config.toml — base_url and api_key fields Run OpenManus with a test task. A successful response confirms the setup is working. OpenManus terminal showing a successful response from CometAPI # Use Pi with CometAPI Source: https://apidoc.cometapi.com/integrations/pi Use this guide to configure Pi with CometAPI by setting the base URL, API key, and model or provider options. [Pi](https://github.com/earendil-works/pi) is the Pi Agent Harness project. Its `@earendil-works/pi-coding-agent` package provides an interactive coding agent CLI with file, shell, edit, write, session, print, JSON, RPC, and SDK workflows. Pi can load custom providers from `~/.pi/agent/models.json`, so you can add CometAPI as OpenAI-compatible provider entries without changing Pi source code. Official references: * [Pi repository](https://github.com/earendil-works/pi) * [Pi quickstart](https://github.com/earendil-works/pi/blob/main/packages/coding-agent/docs/quickstart.md) * [Pi providers](https://github.com/earendil-works/pi/blob/main/packages/coding-agent/docs/providers.md) * [Pi custom models](https://github.com/earendil-works/pi/blob/main/packages/coding-agent/docs/models.md) * [Pi CLI usage](https://github.com/earendil-works/pi/blob/main/packages/coding-agent/docs/usage.md) Model availability changes over time. Replace `your-model-id` with an available model ID from the [CometAPI Models page](/overview/models). ## Prerequisites * Node.js `>=22.19.0` * npm * A CometAPI account with an active API key from the [dashboard](https://www.cometapi.com/console/token) * Pi installed from the official npm package ## Understand runtime permissions Pi runs with the permissions of the user and process that launches it. Start Pi in the project directory you want it to work on, keep a rollback path such as git, and use a container or sandbox if you need stronger filesystem, process, network, or credential boundaries. ## Configure the provider Install Pi globally with npm: ```bash theme={null} npm install -g --ignore-scripts @earendil-works/pi-coding-agent ``` Confirm that the CLI is available: ```bash theme={null} pi --version ``` Store your CometAPI API key in the `COMETAPI_KEY` environment variable: ```bash theme={null} read -rsp "CometAPI API key: " COMETAPI_KEY printf '\n' export COMETAPI_KEY ``` Add the export command to your shell profile if you want it to persist across terminal sessions. Do not commit API keys to version control. Create `~/.pi/agent/models.json` if it does not exist. If the file already contains providers, merge the `cometapi-responses` and `cometapi-chat` entries into the existing `providers` object: ```json theme={null} { "providers": { "cometapi-responses": { "name": "CometAPI Responses", "baseUrl": "https://api.cometapi.com/v1", "api": "openai-responses", "apiKey": "$COMETAPI_KEY", "models": [ { "id": "your-model-id", "name": "CometAPI Responses model" } ] }, "cometapi-chat": { "name": "CometAPI Chat Completions", "baseUrl": "https://api.cometapi.com/v1", "api": "openai-completions", "apiKey": "$COMETAPI_KEY", "models": [ { "id": "your-model-id", "name": "CometAPI Chat model" } ] } } } ``` Use `cometapi-responses` for models or workflows that require the OpenAI Responses API. Use `cometapi-chat` for OpenAI Chat Completions-compatible models. Pi resolves `$COMETAPI_KEY` at request time. Keep the API key in your environment or in your own secrets workflow. List the models that Pi can see for the Responses provider: ```bash theme={null} pi --list-models cometapi-responses ``` Run a short one-shot prompt with the Responses provider: ```bash theme={null} pi --provider cometapi-responses --model your-model-id -p "Reply with one short sentence confirming the Responses connection." ``` List the models that Pi can see for the Chat Completions provider: ```bash theme={null} pi --list-models cometapi-chat ``` Run a short one-shot prompt with the Chat Completions provider: ```bash theme={null} pi --provider cometapi-chat --model your-model-id -p "Reply with one short sentence confirming the Chat Completions connection." ``` For interactive use, start Pi in your project and select the CometAPI provider and model with `/model`. If you edit `models.json` during an interactive session, open `/model` again so Pi reloads the custom model entries. ## Troubleshooting Confirm that `~/.pi/agent/models.json` is valid JSON and that each provider entry is inside the top-level `providers` object. Run `pi --list-models cometapi-responses` or `pi --list-models cometapi-chat` after saving the file. Confirm that `COMETAPI_KEY` is set in the same shell session that launches Pi. If you use a shell profile, open a new terminal or source the profile before running Pi. Use `https://api.cometapi.com/v1` as the `baseUrl` in `models.json`. Do not point Pi at the dashboard URL or omit the `/v1` suffix for OpenAI-compatible routes. Check your Node.js version with `node --version`. The Pi package requires Node.js `>=22.19.0`. Use the provider entry whose `api` field matches the route your model supports. `openai-responses` uses the Responses API, while `openai-completions` uses Chat Completions. Pi runs with the permissions of the user and process that launched it. Run Pi inside a container or sandbox when you need stronger boundaries around files, processes, network access, or credentials. ## Related resources * [CometAPI quick start](/overview/quick-start) * [CometAPI Models page](/overview/models) * [Pi custom models](https://github.com/earendil-works/pi/blob/main/packages/coding-agent/docs/models.md) * [Pi CLI usage](https://github.com/earendil-works/pi/blob/main/packages/coding-agent/docs/usage.md) # Use Pot with CometAPI Source: https://apidoc.cometapi.com/integrations/pot-translation Use this guide to configure Pot with CometAPI by setting the base URL, API key, and model or provider options. Pot is a cross-platform translation and OCR application. Connect it to CometAPI to power AI translation with any supported model. ## Prerequisites * A CometAPI account with an active API key — [get yours here](https://www.cometapi.com/console/token) * Pot installed — [download here](https://pot-app.com/) Log in to the [CometAPI console](https://www.cometapi.com/console/token). Click **Add API Key** and copy your CometAPI API key. CometAPI dashboard showing the Add API Key button CometAPI API key details with base URL Open Pot's menu, go to **Service Settings → Add Built-in Service**, select **OpenAI**, and enable **Stream Output**. Pot service settings panel Selecting OpenAI service with stream enabled * **API Address**: `https://api.cometapi.com/v1/chat/completions` * **API Key**: paste your CometAPI API key * **Model**: set the current model ID you want to use Click **Save**. Pot API configuration fields filled in Select any text and trigger a translation. A successful response confirms the integration is working. Pot showing a successful AI translation result If the call fails, double-check your API key and the endpoint URL, or contact [CometAPI support](https://www.cometapi.com). You can type any current CometAPI model ID directly into the **Model** field — for example, a GPT, Claude, Gemini, or DeepSeek model from the [CometAPI Models page](/overview/models). # Use Promptfoo with CometAPI Source: https://apidoc.cometapi.com/integrations/promptfoo Use this guide to configure Promptfoo with CometAPI by setting the base URL, API key, and model or provider options. [Promptfoo](https://www.promptfoo.dev/) is a framework for prompt evaluation, regression testing, and AI red teaming. Promptfoo includes a `cometapi` provider that calls CometAPI through OpenAI-compatible endpoints. ## Prerequisites * Node.js 18+ * Promptfoo installed locally or run through `npx` * A CometAPI account with an active API key — [get yours in the dashboard](https://www.cometapi.com/console/token) * A model ID from the [CometAPI Models page](/overview/models) ## Configure the integration Set `COMETAPI_KEY` before you run evaluations: ```bash theme={null} read -rsp "CometAPI API key: " COMETAPI_KEY printf '\n' export COMETAPI_KEY ``` Promptfoo uses the following provider ID format for CometAPI: ```yaml theme={null} providers: - cometapi:: ``` Use these provider types: | Type | Use case | | ------------ | ------------------------------------------------ | | `chat` | Chat completions, vision, and multimodal prompts | | `completion` | Text completion models | | `embedding` | Text embedding evaluations | | `image` | Image generation evaluations | You can also use `cometapi:your-model-id` for the default chat mode. The following command runs a one-prompt chat evaluation: ```bash theme={null} npx promptfoo@latest eval \ --prompts "Write a concise release note for {{feature}}" \ --vars feature="a unified API dashboard" \ -r cometapi:chat:your-model-id ``` The following `promptfooconfig.yaml` evaluates the same prompt against a CometAPI model: ```yaml theme={null} prompts: - "Classify this support request: {{message}}" providers: - id: cometapi:chat:your-model-id config: temperature: 0.2 max_tokens: 256 tests: - vars: message: "The API key works locally but fails in production." assert: - type: contains-any value: - authentication - configuration ``` Run the config file with Promptfoo: ```bash theme={null} npx promptfoo@latest eval -c promptfooconfig.yaml ``` ## Provider examples Use a provider type that matches the model behavior that you want to evaluate: ```yaml theme={null} providers: - cometapi:chat:your-model-id - cometapi:completion:your-model-id - cometapi:embedding:your-model-id - cometapi:image:your-model-id ``` For multimodal tests, keep the `chat` provider type and pass image variables through Promptfoo test variables. ## Troubleshooting Confirm that `COMETAPI_KEY` is exported in the same shell session that runs `promptfoo eval`. Use `chat` for conversational and multimodal models, `embedding` for embedding models, and `image` for image generation models. Replace `your-model-id` with an exact model ID from the [CometAPI Models page](/overview/models). ## Related resources * [Promptfoo CometAPI provider](https://www.promptfoo.dev/docs/providers/cometapi/) * [CometAPI quick start](/overview/quick-start) * [CometAPI Models page](/overview/models) # Use uTools ChatGPT Friend with CometAPI Source: https://apidoc.cometapi.com/integrations/utools-chatgpt-friend Use this guide to configure uTools ChatGPT Friend with CometAPI by setting the base URL, API key, and model or provider options. uTools ChatGPT Friend is a uTools plugin that brings AI chat to your desktop quick-launch bar. Connect it to CometAPI, then choose the model you want from the [Models page](/overview/models). ## Prerequisites * A CometAPI account with an active API key — [get yours here](https://www.cometapi.com/console/token) * uTools installed — [download here](https://u.tools/) * ChatGPT Friend plugin — [get it here](https://www.u-tools.cn/plugins/detail/ChatGPT.%E5%A5%BD%E5%8F%8B/index.html) Log in to the [CometAPI console](https://www.cometapi.com/console/token). Click **Add API Key** and copy your CometAPI API key. CometAPI dashboard showing the Add API Key button CometAPI API key details with base URL Open the ChatGPT Friend plugin in uTools. In the settings: * **Interface Address**: `https://api.cometapi.com` * **API Key**: paste your CometAPI API key Click **Save**. ChatGPT Friend settings with interface address and API key filled in Type a message in the chat input and send it. A successful reply confirms the integration is working. ChatGPT Friend showing a successful AI response If the call fails, verify your API key and the interface address, or contact [CometAPI support](https://www.cometapi.com). # Connect Zapier to CometAPI Source: https://apidoc.cometapi.com/integrations/zapier Use this guide to connect Zapier to CometAPI by setting the base URL, API key, and model or provider options. Zapier connects CometAPI to thousands of apps — automate AI-powered workflows without writing code. ## Prerequisites * A CometAPI account with an active API key — [get yours here](https://www.cometapi.com/console/token) * A Zapier account — [sign up here](https://zapier.com/app/home) Log in to the [CometAPI console](https://www.cometapi.com/console/token). Click **Add API Key** and copy your CometAPI API key. CometAPI dashboard showing the Add API Key button CometAPI API key details with base URL In Zapier, create a new Zap. In the workflow editor, click **Add Step** and search for **CometAPI**. Zapier workflow editor with Add Step button Zapier search results showing the CometAPI app CometAPI action selection screen * **Action Event**: select **Generate AI Response** * **Account**: click **Connect a new account** and paste your CometAPI API key Zapier account connection dialog with API key field Click **Continue**, choose the current model you want to use, then click **Continue** again and run **Test Step**. Zapier model selection step Zapier test result showing a successful AI response A successful test result confirms the integration. Click **Publish** to activate your Zap. If the call fails, double-check your API key, or contact [CometAPI support](https://www.cometapi.com). CometAPI appears as a native Zapier app, so no custom HTTP action is needed. You can chain it with Gmail, Google Sheets, Slack, and thousands of other Zapier integrations. # Use Zotero with CometAPI Source: https://apidoc.cometapi.com/integrations/zotero Use this guide to configure Zotero with CometAPI by setting the base URL, API key, and model or provider options. Zotero is a reference management tool for researchers. The **Zotero GPT** plugin adds AI-powered reading, summarization, and Q\&A capabilities — powered by CometAPI. ## Prerequisites * A CometAPI account with an active API key — [get yours here](https://www.cometapi.com/console/token) * Zotero desktop app — [download here](https://www.zotero.org/download/) * Zotero browser connector extension — [get it here](https://www.zotero.org/download/) * `zotero-gpt.xpi` plugin file — [download from the Zotero GPT releases page](https://github.com/MuiseDestiny/zotero-gpt/releases) In your browser's extensions panel, search for and install the **Zotero Connector**. Browser extension panel with Zotero search Zotero Connector extension installed in browser Log in to the [CometAPI console](https://www.cometapi.com/console/token). Click **Add API Key** and copy your CometAPI API key. CometAPI dashboard showing the Add API Key button CometAPI API key details with base URL In Zotero, go to **Tools → Plugins → Install Plugin From File** and select the `zotero-gpt.xpi` file you downloaded. Open the Zotero GPT plugin settings: * **API Address**: `https://api.cometapi.com` * **API Key**: paste your CometAPI API key * **Model**: select or type the model you want to use Zotero GPT settings with API address and key configured Open a paper in Zotero and use the GPT panel to ask a question or request a summary. A successful AI response confirms the integration is working. Zotero GPT responding to a question about an open paper If the call fails, verify your API key and address, or contact [CometAPI support](https://www.cometapi.com).