# 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\}` generates an image with a native BFL-format request. Requests are asynchronous by default. Store the top-level response `id`, then poll [`GET /flux/v1/get_result`](/api/image/flux/flux-query) with that task ID. To wait for the image in the same request, send `"async": false` in the JSON body. A successful synchronous response contains `status: "Ready"` and the image URL in `result.sample`. 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. The optional `async` field controls how the request returns. Use the JSON boolean `false` for synchronous generation. Use `true` or omit the field for asynchronous generation. Do not send a string such as `"false"`. 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`. ## Generate synchronously Select **Synchronous text to image (FLUX.2 Pro)** in the request examples to send `"async": false`. Keep the connection open while the image is generated. The example uses a 300-second client timeout; this is a client setting, not a completion deadline. When the response has `status: "Ready"`, read `result.sample` directly. No result polling is needed. If the request fails, handle the HTTP error before reading the result. Do not combine `async: false` with `webhook_url` or `webhook_secret`. Synchronous requests return the result directly and reject these webhook fields. ## Submit asynchronously and poll When `async` is `true` or omitted, the create response returns a task ID while generation continues. 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. > [!WARNING] > > 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`. > [!WARNING] > > `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. > [!TIP] > > For step-by-step examples, see [Use Gemini image models](/api/image/gemini/generate-image-guide). > [!WARNING] > > 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. > [!NOTE] > > `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. > [!NOTE] > > 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 (gemini-nano-banana-2.1, 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 > [!NOTE] > > * **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... } ``` *** ## Available Gemini image models CometAPI supports multiple Gemini image models: * **gemini-nano-banana-2.1** - Latest Nano Banana model with enhanced image generation capabilities * **gemini-3.1-flash-image-preview** - Fast image generation model * **gemini-3-pro-image-preview** - High-quality image generation model Replace the model ID in the examples below with your preferred model. *** ## 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"] } }' ``` > [!NOTE] > > * 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](https://mintcdn.com/cometapi/OukMcVwzR05umRJn/images/image/gemini/6100640_569419.png?fit=max\&auto=format\&n=OukMcVwzR05umRJn\&q=85\&s=02d820e809bd8e21e3b7b0c58592c6ab) ![Generated output](https://mintcdn.com/cometapi/OukMcVwzR05umRJn/images/image/gemini/6100640_569420.png?fit=max\&auto=format\&n=OukMcVwzR05umRJn\&q=85\&s=b8f128a921f62619b575926da824fd43) ```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](https://mintcdn.com/cometapi/OukMcVwzR05umRJn/images/image/gemini/6100640_569429.png?fit=max\&auto=format\&n=OukMcVwzR05umRJn\&q=85\&s=2a1ea93ce3477491d8014283896c31e2) *** ## 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"} } }' ``` > [!NOTE] > > 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 > **Prompt Optimization** > > Specify style keywords (e.g., "cyberpunk, film grain, low contrast"), aspect ratio, subject, background, lighting, and detail level. > **Base64 Format** > > 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. > **Force Image Output** > > Set `"responseModalities"` to `["IMAGE"]` only to guarantee image output without text. > **Why is my image blurry or lower resolution?** > > 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`. > [!WARNING] > > 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 images with Grok Imagine Image 2.0, including quality, aspect ratio, resolution, image-count, and response-format controls. Use this route to create images from text with Grok image models. The request body uses `application/json`. `model` and `prompt` are required. ## Choose a model Choose a Grok image model ID from the [Models page](/overview/models). The API examples use `grok-imagine-image-2.0`. `quality` is available only with `grok-imagine-image-2.0` and accepts `low` or `medium`. Set it explicitly when your application depends on a particular quality level. When `resolution` is omitted for Image 2.0, CometAPI uses `1k`. ## 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 from 1 through 10 images. The default is `1`. * Use `response_format` to return temporary URLs or Base64-encoded image data. For model-specific behavior, see the [xAI image generation guide](https://docs.x.ai/developers/model-capabilities/images/generation). > [!NOTE] > > Download URL results promptly after the request completes. Generated image URLs are temporary. Use `b64_json` when your application needs the image bytes in the API response. # 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 > **[Create an image](/api/image/openai/images)** > > Generate images with an OpenAI-compatible request. > **[Create image edit](/api/image/openai/image-editing)** > > Edit images with an OpenAI-compatible request. > **[Generate images with Gemini](/api/image/gemini/gemini-generates-image)** > > Generate or edit images with Gemini format. > **[Start with Midjourney API](/api/image/midjourney/midjourney-api-quick-start)** > > Submit and poll Midjourney image tasks. > **[Generate a Flux image](/api/image/flux/flux-generate-image)** > > Generate Flux images through CometAPI. > **[Generate a Bria image](/api/image/bria/generate-image)** > > Use Bria image generation tools. > **[Create a Replicate prediction](/api/image/replicate/create-predictions-general)** > > Run Replicate-format image prediction requests. > **[Create Seedream images](/api/image/seededit-seedream/bytedance-image-generation)** > > 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. > [!NOTE] > > 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. > [!TIP] > > 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 > [!NOTE] > > 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 > **Invalid model ID** > > Choose an image-capable model from the [Models page](/overview/models). > **Unsupported size** > > Use a size that the selected image endpoint accepts. > **Expired result URL** > > Download generated assets before provider links expire. > **Upload too large** > > Use image URLs or smaller files instead of large base64 payloads. > **Missing image data** > > Check both `b64_json` and `url` fields because output shape can differ by model. ## Error codes and retry strategy > **400** > > Do not retry until the prompt, size, or image input is fixed. > **401** > > Do not retry until the API key is present and valid. > **404** > > Check the base URL, path, and model ID before retrying. > **413** > > Reduce upload size before retrying. > **429** > > Retry with exponential backoff and reduce concurrency. > **500 or 503** > > Retry with backoff for transient provider or service errors. > [!TIP] > > 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 > **[Models page](/overview/models)** > > Read how CometAPI exposes model IDs in the docs. > **[Model directory](https://www.cometapi.com/models/)** > > Browse model availability and capabilities. > **[Pricing](https://www.cometapi.com/pricing/)** > > 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 > [!TIP] > > 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 > [!NOTE] > > 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 **1. Submit the image-generation task** Send the subject image list and prompt, then store the returned task id. **2. Poll the task** Poll the returned task with the matching Kling image query path until the task reaches a terminal state. **3. Persist the result** Save the generated image into your own storage if you need durable access. > [!TIP] > > 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. > [!NOTE] > > 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 **1. Create the task** Submit `POST /kling/v1/images/omni-image` and store the returned `data.task_id`. **2. Query the task** Poll [GET /kling/v1/images/omni-image/](/api/image/kling/omni-image-query) until `data.task_status` is `succeed` or `failed`. **3. Persist the images** 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`. > [!NOTE] > > 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 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) > [!WARNING] > > `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 **1. Create the follow-up task** Send `taskId` and `customId`, then store the new returned task id. **2. Poll the new task** Query [Fetch Single Task](./task-fetching-api/fetch-single-task) again until the action finishes. **3. Handle modal-only actions** 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 **1. Submit the blend task** Send the source images through the blend endpoint and store the returned task id. **2. Poll the task** Use [Fetch Single Task](./task-fetching-api/fetch-single-task) until the task reaches a terminal state. **3. Continue from the result** 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 **1. Submit the image** Upload or reference the image you want Midjourney to describe and store the returned task id. **2. Poll the describe task** Use [Fetch Single Task](./task-fetching-api/fetch-single-task) until the task completes and returns prompt-like output. **3. Reuse the generated prompt** 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 **1. Submit the imagine task** Send the prompt and store the returned task id. **2. Poll until the task finishes** Use [Fetch Single Task](./task-fetching-api/fetch-single-task) until the task reaches `SUCCESS`, `MODAL`, or `FAILURE`. **3. Continue with post-processing** 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": "🔄" } ] } ``` > [!WARNING] > > `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. > [!WARNING] > > 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") | > [!TIP] > > 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 **1. Submit the editor task** Choose the editing mode, send the prompt and source data, then store the returned task id. **2. Poll the task** Use [Fetch Single Task](./task-fetching-api/fetch-single-task) until the task reaches a terminal state. **3. Continue from the result** 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 **1. Submit the video task** Start the render and store the returned task id. **2. Poll until the task finishes** Use [Fetch Single Task](./task-fetching-api/fetch-single-task) until the task reaches a terminal state and exposes the final video URL. **3. Persist the output** 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 **1. Use single-task polling for hot paths** For one active task, prefer [Fetch Single Task](./fetch-single-task), because it is simpler and faster. **2. Use condition-based listing for batch checks** Send your filter conditions through this endpoint when you need to inspect multiple Midjourney tasks in one request. **3. Follow up on interesting tasks** When the batch result shows tasks that need deeper inspection or continuation, switch back to [Fetch Single Task](./fetch-single-task) and [Action](../action). > [!TIP] > > 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 **1. Create the task** Send `POST /v1/images/generations` with `async: true`, then store `data.task_id`. **2. Poll the task** Call this endpoint with the stored task ID until `data.status` is `success` or `failure`. **3. Read the image data** 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 `gpt-image-2.5-sunburst` or `gpt-image-2.5-flare` when you need transparent backgrounds or the `xhigh` and `max` quality levels * Use the same request shape with other image model families, such as Qwen-Image, Doubao Seedream, or Grok Imagine; start with `model` and `prompt` * 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` * 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` * `quality` accepts `low`, `medium`, `high`, and `auto` on GPT image models; `gpt-image-2.5-sunburst` and `gpt-image-2.5-flare` also accept `xhigh` and `max` * `output_compression` applies when `output_format` is `webp` or `jpeg`; it has no effect on `png` * `partial_images` applies only when `stream` is `true` * Follow the OpenAI image generation guide for the latest model-specific options * Other image model families can return the image in `url` instead of `b64_json`; read the field that each result item contains ## Generate a transparent background Set `background` to `transparent` to generate an isolated subject with no background fill. This is supported on `gpt-image-2.5-sunburst` and `gpt-image-2.5-flare`. Transparency needs an output format with an alpha channel. Set `output_format` to `png` or `webp`. JPEG has no alpha channel, so a transparent request with `output_format: "jpeg"` is rejected. The response returns base64 image data in `b64_json` with an alpha channel. Decode it to save the file: ```python theme={null} import base64 import os from openai import OpenAI client = OpenAI( base_url="https://api.cometapi.com/v1", api_key=os.environ["COMETAPI_KEY"], ) result = client.images.generate( model="gpt-image-2.5-sunburst", prompt="A single red apple, centered, isolated subject.", quality="low", size="1024x1024", background="transparent", output_format="png", ) with open("apple.png", "wb") as f: f.write(base64.b64decode(result.data[0].b64_json)) ``` Set `background` to `opaque` to force a solid background, or `auto` to let the model decide. The response echoes the applied value in the top-level `background` field. > [!WARNING] > > 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 **1. Create the prediction** Submit the path model id and the `input` object through this endpoint. **2. Store the prediction id** Save the returned `id`, because you need it for later polling. **3. Poll the prediction** 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 **1. Create the prediction first** Start with [Create a Replicate prediction](./create-predictions-general). **2. Poll by prediction id** Keep querying until `status` becomes terminal and `output` is either populated or a provider error is returned. **3. Persist finished assets** 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 > [!WARNING] > > 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 **1. Create the task** Send `POST /v1/images/generations` with `async: true`, then store `data.task_id`. **2. Poll the task** Call this endpoint with the stored task ID until `data.status` is `success` or `failure`. **3. Read the image data** 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. > [!WARNING] > > 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 Call Claude through the CometAPI Messages endpoint with text and image input, adaptive thinking, prompt caching, streaming, and tools. Use `POST /v1/messages` to send Claude requests in the Anthropic Messages format. The examples configure the official Anthropic SDK with the CometAPI base URL and read your API key from `$COMETAPI_KEY`. > [!TIP] > > For field definitions and model-specific options, see the official > [Messages API reference](https://platform.claude.com/docs/en/api/messages/create). > For OpenAI-compatible requests, see [Chat Completions](/api/text/chat). > [!NOTE] > > Authenticate with `x-api-key` or `Authorization: Bearer`. The Anthropic SDK uses > `x-api-key`. The HTTP examples include `anthropic-version: 2023-06-01`. ## Quick start The following examples request three search queries. Set `$COMETAPI_KEY` before running them. Install `anthropic` for Python or `@anthropic-ai/sdk` for JavaScript: ```bash Shell 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": "claude-opus-5", "max_tokens": 1000, "messages": [ { "role": "user", "content": "Suggest three search queries about renewable energy storage." } ] }' ``` ```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-opus-5", max_tokens=1000, messages=[ { "role": "user", "content": "Suggest three search queries about renewable energy storage.", }, ], ) for block in message.content: if block.type == "text": print(block.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-opus-5", "max_tokens": 1000, "messages": [ { "role": "user", "content": "Suggest three search queries about renewable energy storage." } ] }); for (const block of message.content) { if (block.type === "text") console.log(block.text); } ``` The response contains a `content` array. Read blocks whose `type` is `text`; thinking and tool blocks can appear before the text. ## Control adaptive thinking Set `thinking.type` to `adaptive` and choose an `output_config.effort` value. The following example uses `xhigh` and reads the completed message from a stream: ```python theme={null} import os import anthropic client = anthropic.Anthropic( base_url="https://api.cometapi.com", api_key=os.environ["COMETAPI_KEY"], ) with client.messages.stream( model="claude-opus-5", max_tokens=4096, messages=[ { "role": "user", "content": "A shop sells notebooks for $7 each. Buying three earns a $4 discount. A customer pays $20 for three notebooks. Calculate the total and the change, and explain your steps.", }, ], thinking={ "type": "adaptive", }, output_config={ "effort": "xhigh", }, ) as stream: message = stream.get_final_message() for block in message.content: if block.type == "text": print(block.text) ``` Thinking contributes to the `max_tokens` output limit. Leave room for the final answer as well as thinking. A response can contain text without a visible thinking block. Preserve any returned thinking blocks unchanged in conversation history. For the model-specific thinking configuration, see [Thinking](https://platform.claude.com/docs/en/build-with-claude/extended-thinking). The examples omit `temperature`, `top_p`, and `top_k`; consult the selected model's parameter documentation before adding sampling controls. ## Cache prompts Place a cache breakpoint on reference material that you reuse between requests. Save your reference material in a UTF-8 `reference.txt` file before running this example. Use a prefix that meets the selected model's [minimum cacheable length](https://platform.claude.com/docs/en/build-with-claude/prompt-caching#cache-limitations): ```python theme={null} import os from pathlib import Path import anthropic client = anthropic.Anthropic( base_url="https://api.cometapi.com", api_key=os.environ["COMETAPI_KEY"], ) reference = Path("reference.txt").read_text(encoding="utf-8") with client.messages.stream( model="claude-sonnet-5", max_tokens=1024, messages=[ { "role": "user", "content": "How long can customers return damaged books, and what must they provide?", }, ], system=[ { "type": "text", "text": reference, "cache_control": { "type": "ephemeral", }, }, ], ) as stream: message = stream.get_final_message() for block in message.content: if block.type == "text": print(block.text) print(message.usage.model_dump_json()) ``` Run the request again with the same model, reference text, and thinking settings. Inspect the usage counters to determine whether the request reused a prefix: * `cache_creation_input_tokens` counts tokens written to the cache. * `cache_read_input_tokens` counts tokens read from the cache. * `input_tokens` counts input processed outside those cache counters. On repeated requests, `cache_read_input_tokens` reports how many input tokens were read from the cache. The OpenAPI **Prompt Cache** example contains a complete fictional reference that you can save as `reference.txt` to try the sample. ## Stream responses Set `stream: true` for Server-Sent Events. The SDK exposes text fragments as they arrive: ```python theme={null} import os import anthropic client = anthropic.Anthropic( base_url="https://api.cometapi.com", api_key=os.environ["COMETAPI_KEY"], ) with client.messages.stream( model="claude-opus-5", max_tokens=1024, messages=[ { "role": "user", "content": "Write a two-line poem about a comet.", }, ], ) as stream: for text in stream.text_stream: print(text, end="", flush=True) ``` A message stream contains `message_start`, content block events, `message_delta`, and `message_stop`. Content blocks can contain text, thinking, or tool activity. For a text block, `content_block_delta` contains a `text_delta`. Read final usage and the stop reason from `message_delta`. ## Control effort Set `output_config.effort` to guide the amount of reasoning. This example uses `low` for a short explanation and waits for the completed streamed message: ```python theme={null} import os import anthropic client = anthropic.Anthropic( base_url="https://api.cometapi.com", api_key=os.environ["COMETAPI_KEY"], ) with client.messages.stream( model="claude-opus-5", max_tokens=1000, messages=[ { "role": "user", "content": "Summarize the benefit of automated tests in one sentence.", }, ], output_config={ "effort": "low", }, ) as stream: message = stream.get_final_message() for block in message.content: if block.type == "text": print(block.text) ``` Use the official [effort reference](https://platform.claude.com/docs/en/build-with-claude/effort) to choose an effort level. Set `max_tokens` separately to limit output length. ## Use server tools Server tools execute during the API request and return result blocks alongside Claude's answer. **Web Fetch** Fetch a paper and ask Claude to use the retrieved document in its answer. This example streams the response and inspects both the final text and the `web_fetch_tool_result` block: ```python theme={null} import os import anthropic client = anthropic.Anthropic( base_url="https://api.cometapi.com", api_key=os.environ["COMETAPI_KEY"], ) with client.messages.stream( model="claude-sonnet-5", max_tokens=2048, messages=[ { "role": "user", "content": "Fetch https://arxiv.org/abs/1512.03385 and state the paper title and the proposed learning framework in two sentences.", }, ], tools=[ { "type": "web_fetch_20250910", "name": "web_fetch", "max_uses": 3, }, ], ) as stream: message = stream.get_final_message() for block in message.content: if block.type == "text": print(block.text) for block in message.content: if block.type == "web_fetch_tool_result": print(block.model_dump_json()) ``` The response pairs a `server_tool_use` block with a `web_fetch_tool_result` containing the fetched document or a tool error. **Web Search** Search for an official release date and ask Claude to cite its source. This example streams the response, collects the final message, and prints the returned search sources: ```python theme={null} import os import anthropic client = anthropic.Anthropic( base_url="https://api.cometapi.com", api_key=os.environ["COMETAPI_KEY"], ) with client.messages.stream( model="claude-sonnet-5", max_tokens=4096, messages=[ { "role": "user", "content": "Search the web for the official Python 3.14 release date. Answer with the date and cite a source.", }, ], tools=[ { "type": "web_search_20250305", "name": "web_search", "max_uses": 3, }, ], ) as stream: message = stream.get_final_message() for block in message.content: if block.type == "text": print(block.text) for block in message.content: if block.type == "web_search_tool_result": if isinstance(block.content, list): for result in block.content: if result.type == "web_search_result": print(result.title, result.url) ``` The response pairs a `server_tool_use` block with a `web_search_tool_result` containing sources. Read the source titles and URLs from this result block. ## Return client tool results For a client tool, Claude returns a `tool_use` block. Run your application function and send its result in a `tool_result` block with the matching `tool_use_id`. Preserve the complete assistant content between the two requests. This example supplies a fictional order result and asks Claude to use that result: ```python theme={null} import json import os import anthropic client = anthropic.Anthropic( base_url="https://api.cometapi.com", api_key=os.environ["COMETAPI_KEY"], ) tools = [{ "name": "get_order_status", "description": "Look up the status of a demonstration order.", "input_schema": { "type": "object", "properties": { "order_id": { "type": "string", "description": "The order reference.", }, }, "required": ["order_id"], }, }] messages = [{ "role": "user", "content": "Check the status of demo-order-42 using the order tool.", }] with client.messages.stream( model="claude-opus-5", max_tokens=1000, messages=messages, tools=tools, ) as stream: message = stream.get_final_message() tool_call = next(b for b in message.content if b.type == "tool_use") messages.append({ "role": "assistant", "content": [block.model_dump() for block in message.content], }) messages.append({ "role": "user", "content": [{ "type": "tool_result", "tool_use_id": tool_call.id, "content": json.dumps({ "status": "ready_for_pickup", "pickup_code": "COMET42", }), }], }) with client.messages.stream( model="claude-opus-5", max_tokens=1000, messages=messages, tools=tools, ) as stream: follow_up = stream.get_final_message() for block in follow_up.content: if block.type == "text": print(block.text) ``` ## Response example A non-streaming request returns a message object. The following example shows its text and usage fields with an illustrative message identifier: ```json theme={null} { "id": "msg_example", "type": "message", "role": "assistant", "model": "claude-opus-5", "content": [ { "type": "text", "text": "Here are three search queries covering different angles of the topic:\n\n1. **\"grid-scale battery storage cost trends 2024 2025\"**\n — Targets economics and recent price data for lithium-ion and other utility-scale systems.\n\n2. **\"long-duration energy storage technologies comparison flow battery vs compressed air vs thermal\"**\n — Surfaces technical comparisons of options for storage beyond the 4–8 hour range, where lithium-ion becomes less cost-effective.\n\n3. **\"green hydrogen seasonal storage feasibility round-trip efficiency\"**\n — Digs into the viability of hydrogen for multi-week or seasonal balancing, including its efficiency penalties.\n\n**A few tips for refining these:**\n- Add `site:.gov` or `site:.edu` to prioritize research and agency reports (e.g., NREL, IEA, DOE).\n- Append a region like `Europe`, `India`, or `California` if you need location-specific policy or deployment data.\n- Try `filetype:pdf` to pull up technical white papers and government studies directly.\n\nWant me to tailor these toward a specific use case — academic research, investment analysis, or policy work?" } ], "stop_reason": "end_turn", "stop_sequence": null, "usage": { "input_tokens": 23, "cache_creation_input_tokens": 0, "cache_read_input_tokens": 0, "cache_creation": { "ephemeral_5m_input_tokens": 0, "ephemeral_1h_input_tokens": 0 }, "output_tokens": 437, "output_tokens_details": { "thinking_tokens": 50 } } } ``` The stop reason describes the next action. `end_turn` completes the answer, `max_tokens` means output reached the limit, and `tool_use` requests a client tool result. For a server-tool turn that returns `pause_turn`, continue with the returned assistant content unchanged. # 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, structured output, and tool calling. Send conversations through the OpenAI-compatible Chat Completions API. Configure your SDK with `base_url="https://api.cometapi.com/v1"` and your CometAPI API key. The basic, image, streaming, and structured-output examples use `gpt-6-astra`. The function-calling example uses `gpt-6.1-sol`, and the log-probability example uses `gpt-4.1`. > [!NOTE] > > Use the [OpenAI Chat Completions reference](https://developers.openai.com/api/reference/typescript/resources/chat/subresources/completions/methods/create) for parameter definitions. For GPT-6 Astra tool calling, use [Responses](/api/text/responses), following the [OpenAI model guidance](https://developers.openai.com/api/docs/guides/latest-model). *** ## Message roles | Role | Description | | - | - | | `system` | Sets the assistant's behavior and personality. Placed at the start of the conversation. | | `developer` | Provides application instructions. The GPT-6 Astra examples use this role. | | `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. | > [!TIP] > > Place application instructions in a `developer` message before user messages when using the GPT-6 Astra examples. *** ## Send multimodal input Use an array of content parts to send an image with text: ```json theme={null} { "model": "gpt-6-astra", "messages": [ { "role": "user", "content": [ { "type": "text", "text": "Describe the road and surrounding landscape in this image." }, { "type": "image_url", "image_url": { "url": "https://images.unsplash.com/photo-1500530855697-b586d89ba3ee?w=1200", "detail": "high" } } ] } ], "reasoning_effort": "low", "max_completion_tokens": 4096 } ``` Use `image_url.detail` to select image processing detail. This example uses `high`. *** ## Stream responses To receive incremental output, set `stream` to `true`. The response is delivered as **Server-Sent Events (SSE)**. Text arrives in `chat.completion.chunk` objects; this abbreviated example includes the final usage chunk: ```text theme={null} data: {"choices":[{"delta":{"content":"","refusal":null,"role":"assistant"},"finish_reason":null,"index":0,"logprobs":null}],"created":1788765075,"id":"chatcmpl_example","model":"gpt-6-astra-2026-09-03","object":"chat.completion.chunk"} data: {"choices":[{"delta":{"content":"Hi"},"finish_reason":null,"index":0,"logprobs":null}],"created":1788765075,"id":"chatcmpl_example","model":"gpt-6-astra-2026-09-03","object":"chat.completion.chunk"} : Additional text deltas omitted data: {"choices":[{"delta":{},"finish_reason":"stop","index":0,"logprobs":null}],"created":1788765075,"id":"chatcmpl_example","model":"gpt-6-astra-2026-09-03","object":"chat.completion.chunk"} data: {"choices":[],"created":1788765075,"id":"chatcmpl_example","model":"gpt-6-astra-2026-09-03","object":"chat.completion.chunk","usage":{"completion_tokens":12,"completion_tokens_details":{"accepted_prediction_tokens":0,"audio_tokens":0,"reasoning_tokens":0,"rejected_prediction_tokens":0},"prompt_tokens":18,"prompt_tokens_details":{"audio_tokens":0,"cache_write_tokens":0,"cached_tokens":0},"total_tokens":30}} data: [DONE] ``` > [!TIP] > > To include token usage statistics in streaming responses, set `stream_options.include_usage` to `true`. The usage data appears in a final chunk before `[DONE]`. Chunks can have an empty `choices` array; check it before accessing `choices[0]`. *** ## Request structured output Use `response_format` to request structured output: ```json JSON Schema theme={null} { "model": "gpt-6-astra", "messages": [ { "role": "user", "content": "What is the capital of France? Return the answer and your confidence as a number from 0 to 1." } ], "reasoning_effort": "low", "response_format": { "type": "json_schema", "json_schema": { "name": "result", "strict": true, "schema": { "type": "object", "properties": { "answer": { "type": "string", "description": "The answer to the question." }, "confidence": { "type": "number", "description": "Confidence between zero and one." } }, "required": [ "answer", "confidence" ], "additionalProperties": false } } } } ``` ```json JSON Object theme={null} { "model": "gpt-6-astra", "messages": [ { "role": "user", "content": "Return a JSON object with the key answer and the capital of France as its value." } ], "reasoning_effort": "low", "response_format": { "type": "json_object" } } ``` JSON Schema mode specifies the required structure. JSON Object mode requests valid JSON without enforcing your schema. Check for a refusal or a length-limited response before consuming the result. *** ## Call tools and functions Use `gpt-6.1-sol` with a function definition: ```json theme={null} { "model": "gpt-6.1-sol", "messages": [ { "role": "user", "content": "What is the weather in Boston, MA, in celsius? Use the weather tool." } ], "reasoning_effort": "none", "tools": [ { "type": "function", "function": { "name": "get_current_weather", "description": "Get the current weather for a city.", "parameters": { "type": "object", "properties": { "location": { "type": "string", "description": "City and state, for example Boston, MA." }, "unit": { "type": "string", "enum": [ "celsius", "fahrenheit" ], "description": "Temperature unit." } }, "required": [ "location", "unit" ], "additionalProperties": false }, "strict": true } } ], "tool_choice": "auto" } ``` A function call returns `finish_reason: "tool_calls"` and a `message.tool_calls` array. Parse the function's JSON-encoded `arguments`, execute your function, then append the assistant message and a `tool` result message with its matching `tool_call_id`. *** ## Choose request parameters > **Model-specific parameters** > > Use `reasoning_effort` and `max_completion_tokens` with GPT-6 Astra. The Functions and Logprobs examples show the request options for `gpt-6.1-sol` and `gpt-4.1`, respectively. > > For Claude- or Gemini-specific request formats, see [Anthropic Messages](/api/text/anthropic-messages) and [Gemini Generate content](/api/text/gemini-generating-content). > **max\_tokens and max\_completion\_tokens** > > Use `max_completion_tokens` to limit generated tokens for the GPT-6 Astra examples. This includes reasoning and visible output, so allow room for both. `max_tokens` is a legacy parameter. > **Instruction roles** > > Use `developer` for application instructions in the GPT-6 Astra examples. Keep end-user content in `user` messages and preserve previous assistant replies when continuing a conversation. *** ## 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-6-astra", messages=messages, reasoning_effort="low", ) 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. Compare model pricing and choose a model that meets your workload requirements. 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, video input, thinking summaries, Google Search grounding, JSON output, and streaming. Use the Gemini native request format through CometAPI to generate text, send video input, and configure thinking or tools. The examples use `gemini-3.8-flash`. > [!TIP] > > Use Google's [GenerateContent API reference](https://ai.google.dev/api/generate-content) for field definitions and model-specific options. This page shows the CometAPI base URL, authentication, and request examples. > [!NOTE] > > Both `x-goog-api-key` and `Authorization: Bearer` headers are supported for authentication. ## Quick start To use the Google Gen AI SDK or an HTTP client with CometAPI, configure 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` | Use the [GenerateContent text generation guide](https://ai.google.dev/gemini-api/docs/generate-content/text-generation) for native API examples. Keep the `generateContent` request shape when changing the base URL. ## Send video input Send 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. | > [!NOTE] > > For REST and curl requests, use camelCase field names such as `inlineData.mimeType` and `fileData.fileUri`. This example sends inline MP4 data. Replace `` with the base64 contents of your video: ```sh theme={null} curl \ "https://api.cometapi.com/v1beta/models/gemini-3.8-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": 2048, "thinkingConfig": { "thinkingLevel": "LOW" } } } EOF ``` This example analyzes a public MP4 of a flower opening: ```sh theme={null} curl \ "https://api.cometapi.com/v1beta/models/gemini-3.8-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://interactive-examples.mdn.mozilla.net/media/cc0-videos/flower.mp4" } }, { "text": "Analyze this video and list the key scenes." } ] } ], "generationConfig": { "maxOutputTokens": 2048, "thinkingConfig": { "thinkingLevel": "LOW" } } } EOF ``` ## Configure thinking (reasoning) Use `thinkingConfig.thinkingLevel` to guide reasoning depth. The examples below use `LOW` and `MEDIUM`. **Thinking level** This example sets the thinking level to `LOW`: ```sh theme={null} curl \ "https://api.cometapi.com/v1beta/models/gemini-3.8-flash:generateContent" \ -H "Content-Type: application/json" \ -H "x-goog-api-key: $COMETAPI_KEY" \ --data-binary @- <<'EOF' { "contents": [ { "parts": [ { "text": "How does quantum computing work?" } ] } ], "generationConfig": { "thinkingConfig": { "thinkingLevel": "LOW" } } } EOF ``` **Thinking summaries** Set `includeThoughts` to request a thinking summary. When the response includes a summary, its text part has `thought: true`: ```sh theme={null} curl \ "https://api.cometapi.com/v1beta/models/gemini-3.8-flash:generateContent" \ -H "Content-Type: application/json" \ -H "x-goog-api-key: $COMETAPI_KEY" \ --data-binary @- <<'EOF' { "contents": [ { "parts": [ { "text": "What is the 10th Fibonacci number when F(0)=0 and F(1)=1? Briefly verify the result." } ] } ], "generationConfig": { "maxOutputTokens": 4096, "thinkingConfig": { "thinkingLevel": "MEDIUM", "includeThoughts": true } } } EOF ``` > [!NOTE] > > `thinkingBudget` is a numeric control for compatible models, including Gemini 2.5. Use `thinkingLevel` in the Gemini 3 examples and do not send both controls. See Google's [thinking guide](https://ai.google.dev/gemini-api/docs/generate-content/thinking) for model-specific values. ## Stream responses Use `streamGenerateContent?alt=sse` to receive Server-Sent Events. Each `data:` line contains a JSON `GenerateContentResponse` object: ```sh theme={null} curl \ "https://api.cometapi.com/v1beta/models/gemini-3.8-flash:streamGenerateContent?alt=sse" \ -H "Content-Type: application/json" \ -H "x-goog-api-key: $COMETAPI_KEY" \ --no-buffer \ --data-binary @- <<'EOF' { "contents": [ { "parts": [ { "text": "Write a short poem about the stars" } ] } ] } EOF ``` ## Set system instructions Use `systemInstruction` to guide the response. This example requests one equation without additional text: ```sh theme={null} curl \ "https://api.cometapi.com/v1beta/models/gemini-3.8-flash:generateContent" \ -H "Content-Type: application/json" \ -H "x-goog-api-key: $COMETAPI_KEY" \ --data-binary @- <<'EOF' { "contents": [ { "parts": [ { "text": "What is 2+2?" } ] } ], "systemInstruction": { "parts": [ { "text": "You are a math tutor. Answer with exactly one equation and no other text." } ] } } EOF ``` ## Request JSON output Set `responseMimeType` to `application/json` and provide a `responseSchema`. This example requests an array of planets with names and numeric distances: ```sh theme={null} curl \ "https://api.cometapi.com/v1beta/models/gemini-3.8-flash:generateContent" \ -H "Content-Type: application/json" \ -H "x-goog-api-key: $COMETAPI_KEY" \ --data-binary @- <<'EOF' { "contents": [ { "parts": [ { "text": "Return a JSON array of 3 planets with name and average_distance_from_sun_au." } ] } ], "generationConfig": { "responseMimeType": "application/json", "responseSchema": { "type": "ARRAY", "items": { "type": "OBJECT", "properties": { "name": { "type": "STRING", "description": "Name of the planet." }, "average_distance_from_sun_au": { "type": "NUMBER", "description": "Average distance from the Sun, in astronomical units." } }, "required": [ "name", "average_distance_from_sun_au" ] } } } } EOF ``` ## Ground with Google Search Add a `googleSearch` tool to request search grounding. This example asks for the result of the UEFA EURO 2024 final: ```sh theme={null} curl \ "https://api.cometapi.com/v1beta/models/gemini-3.8-flash:generateContent" \ -H "Content-Type: application/json" \ -H "x-goog-api-key: $COMETAPI_KEY" \ --data-binary @- <<'EOF' { "contents": [ { "parts": [ { "text": "Use Google Search to find the winner and final score of the UEFA EURO 2024 final. Cite your sources." } ] } ], "tools": [ { "googleSearch": {} } ], "generationConfig": { "maxOutputTokens": 2048 } } EOF ``` When search is used, inspect the candidate's `groundingMetadata` for search queries, source URLs, and links between sources and response text. ## Preserve conversation content For multi-turn conversations, send the preceding `user` and `model` content in `contents`. The SDK chat examples maintain this history for you. For function calling, return one `functionResponse` for each `functionCall`, with the matching `name` and any returned `id`. Pass the preceding model content back unchanged, including `thoughtSignature` fields. The signature is opaque; do not reconstruct it from displayed text. ## Response example A text response includes generated content and token usage. This abbreviated example omits optional fields: ```json theme={null} { "candidates": [ { "content": { "role": "model", "parts": [ { "text": "AI learns patterns from massive amounts of data to make predictions, solve problems, and generate new content. \n\nIn short: **Data in → Patterns found → Smart predictions out.**" } ] }, "finishReason": "STOP" } ], "usageMetadata": { "promptTokenCount": 9, "candidatesTokenCount": 36, "thoughtsTokenCount": 388, "totalTokenCount": 433 }, "modelVersion": "gemini-3.8-flash" } ``` > [!NOTE] > > `thoughtsTokenCount` reports internal thinking tokens, even when the response does not include a thinking summary. Inspect each content part; a response can contain text, summaries, or function calls. ## Compare request formats Choose the native endpoint for Gemini request and response fields. See [Chat Completions](/api/text/chat) for the OpenAI-compatible format. | Field | Gemini native | OpenAI-compatible chat | | - | - | - | | Conversation input | `contents` with `parts` | `messages` | | Model ID | In the request path | `model` in the request body | | Generated content | `candidates` with `content.parts` | `choices` with `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 > **[Create a chat completion](/api/text/chat)** > > Send OpenAI-compatible chat messages with a messages array. > **[Create a model response](/api/text/responses)** > > Use reasoning, multimodal output, and built-in tools through the Responses API. > **[Create a Message](/api/text/anthropic-messages)** > > Call Claude-compatible Messages workflows with provider-native fields. > **[Generate content](/api/text/gemini-generating-content)** > > 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. > [!NOTE] > > 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 > [!NOTE] > > 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 > **Missing or invalid API key** > > Send `Authorization: Bearer $COMETAPI_KEY`. > **Wrong base URL** > > Use `https://api.cometapi.com/v1` for OpenAI-compatible requests. > **Wrong model type** > > Choose a text-capable model from the [Models page](/overview/models). > **Provider-specific parameter error** > > Remove optional fields, then add the fields back one at a time. ## Error codes and retry strategy > **400** > > Do not retry until the request body is fixed. > **401** > > Do not retry until the API key is present and valid. > **404** > > Check the base URL, path, and model ID before retrying. > **429** > > Retry with exponential backoff and reduce concurrency. > **500 or 503** > > Retry with backoff for transient provider or service errors. > [!TIP] > > 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 > **[Models page](/overview/models)** > > Read how CometAPI exposes model IDs in the docs. > **[Model directory](https://www.cometapi.com/models/)** > > Browse model availability and capabilities. > **[Pricing](https://www.cometapi.com/pricing/)** > > 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 model responses and conversation history with built-in tools and function calling. Use the Responses API to send text, images, files, and conversation history with `gpt-6-astra`. The examples also demonstrate web search, custom function calls, structured output, reasoning, and streaming. > [!NOTE] > > The [OpenAI Responses reference](https://developers.openai.com/api/reference/typescript/resources/responses/methods/create) describes the full API format; the examples here configure that format for CometAPI. *** ## Continue a conversation For a text-only conversation, keep the user messages and assistant text replies, then add the next user message: ```python theme={null} import os from openai import OpenAI client = OpenAI( base_url="https://api.cometapi.com/v1", api_key=os.environ["COMETAPI_KEY"], ) input_items = [ {"role": "user", "content": "My project is named Cedar and uses Python. Remember these two facts."} ] response = client.responses.create( model="gpt-6-astra", input=input_items, reasoning={"effort": "low"}, ) input_items.append({"role": "assistant", "content": response.output_text}) input_items.append({ "role": "user", "content": "What is my project's name and programming language?", }) follow_up = client.responses.create( model="gpt-6-astra", input=input_items, reasoning={"effort": "low"}, ) print(follow_up.output_text) ``` `response.output_text` is an SDK convenience property that combines assistant text from the response. Function-calling conversations also need their tool-call and result items, as described below. *** ## Use web search Add a `web_search` tool to search for information and include source citations: ```python theme={null} import os from openai import OpenAI client = OpenAI( base_url="https://api.cometapi.com/v1", api_key=os.environ["COMETAPI_KEY"], ) response = client.responses.create( model="gpt-6-astra", input="Search the web for the NASA Artemis II mission overview and cite the official NASA page.", tools=[ { "type": "web_search", }, ], reasoning={ "effort": "low", }, ) print(response.output_text) ``` Inspect the returned `web_search_call` items and the message's URL annotations when your application needs search results or citations. Other built-in tools require their own configuration; see the [OpenAI tools guide](https://developers.openai.com/api/docs/guides/tools). *** ## Call custom functions Define the function arguments and let the model request the function: ```python theme={null} import os from openai import OpenAI client = OpenAI( base_url="https://api.cometapi.com/v1", api_key=os.environ["COMETAPI_KEY"], ) response = client.responses.create( model="gpt-6-astra", input="What is the weather in Boston, MA, in celsius? Use the weather tool.", tools=[ { "type": "function", "name": "get_current_weather", "description": "Get the current weather for a city.", "parameters": { "type": "object", "properties": { "location": { "type": "string", "description": "City and state, for example Boston, MA.", }, "unit": { "type": "string", "enum": [ "celsius", "fahrenheit", ], "description": "Temperature unit.", }, }, "required": [ "location", "unit", ], "additionalProperties": False, }, "strict": True, }, ], tool_choice="auto", reasoning={ "effort": "low", }, ) print(response.output) ``` A function call appears as a `function_call` output item. Its `arguments` field is a JSON-encoded string. Execute your function, then build the next request from the original input and returned output items without their response-item `id` fields. Keep the function's `name`, `arguments`, and `call_id`, and append a `function_call_output` item with the matching `call_id` and your result in `output`. *** ## Request structured output Use `text.format` to request JSON that follows a schema: ```python theme={null} import os from openai import OpenAI client = OpenAI( base_url="https://api.cometapi.com/v1", api_key=os.environ["COMETAPI_KEY"], ) response = client.responses.create( model="gpt-6-astra", 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", "description": "Programming language name.", }, "use_case": { "type": "string", "description": "Main use case for the language.", }, }, "required": [ "name", "use_case", ], "additionalProperties": False, }, "description": "Three programming languages and their main uses.", }, }, "required": [ "languages", ], "additionalProperties": False, }, }, }, reasoning={ "effort": "low", }, ) print(response.output_text) ``` Check that the response completed and did not refuse the request before parsing the JSON. A response that reaches its output-token limit can be incomplete. *** ## Configure reasoning Set `reasoning.effort` to select the model's reasoning effort: ```python theme={null} import os from openai import OpenAI client = OpenAI( base_url="https://api.cometapi.com/v1", api_key=os.environ["COMETAPI_KEY"], ) response = client.responses.create( model="gpt-6-astra", input="Solve this step by step: what is 15% of 240?", reasoning={ "effort": "high", }, ) print(response.output_text) ``` The examples use `low` for general tasks and `high` for the reasoning example. `max_output_tokens` includes both reasoning and visible output tokens. *** ## Stream responses Set `stream` to `true` to receive server-sent events: ```python theme={null} import os from openai import OpenAI client = OpenAI( base_url="https://api.cometapi.com/v1", api_key=os.environ["COMETAPI_KEY"], ) stream = client.responses.create( model="gpt-6-astra", input="Tell me a three sentence bedtime story about a unicorn.", reasoning={ "effort": "low", }, stream=True, ) for event in stream: if event.type == "response.output_text.delta": print(event.delta, end="") ``` A text response includes lifecycle events such as `response.created`, `response.in_progress`, and `response.completed`. Text arrives in `response.output_text.delta` events. Tool and reasoning events depend on the request, so handle events by their `type` rather than assuming every response has the same sequence. *** > [!TIP] > > See the OpenAI guides for [image input](https://developers.openai.com/api/docs/guides/images-vision), [file input](https://developers.openai.com/api/docs/guides/file-inputs), [structured outputs](https://developers.openai.com/api/docs/guides/structured-outputs), [function calling](https://developers.openai.com/api/docs/guides/function-calling), [conversation state](https://developers.openai.com/api/docs/guides/conversation-state), and [reasoning](https://developers.openai.com/api/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 video from text, reference images, or first and last frames with a 720p or 1080p size preset. Create a Flux 3 video from text, reference images, or first and last frames. Store the returned `id` to poll the task and download the completed video. `POST /v1/videos` uses `multipart/form-data`. Send controls as form fields. For image inputs, use reference image URLs or opening and closing frames. Keep `input_reference` separate from `first_frame` and `last_frame`. ## 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 `input_reference` URL | `seconds`, `size` | | Ordered keyframes | `model=flux-3`, `prompt`, repeated `input_reference` URLs | `seconds`, `size` | | Uploaded opening frame | `model=flux-3`, `prompt`, one `first_frame` file | `seconds`, `size` | | First-and-last-frame video | `model=flux-3`, `prompt`, `first_frame`, `last_frame` | `seconds`, `size` | ## Use reference images The `input_reference` field accepts publicly accessible HTTPS image URLs only. Send it once for a single image, or repeat it in keyframe order for multiple images. Use one URL per field, up to 10 URLs in total. Describe the motion, camera behavior, and visual details that the generated video should preserve from the reference image. The request samples at the top of this page show single-image and multiple-image inputs. The following request uses two images in their submitted order: ```bash theme={null} curl \ https://api.cometapi.com/v1/videos \ -H "Authorization: Bearer $COMETAPI_KEY" \ --form-string 'model=flux-3' \ --form-string 'prompt=Move smoothly through the supplied reference images in their given order. Preserve recognizable subjects and visual details as the scene changes. Keep the camera movement gentle.' \ --form-string 'seconds=5' \ --form-string 'size=1280x720' \ --form-string 'input_reference=https://apidoc.cometapi.com/images/image/gemini/6100640_569429.png' \ --form-string 'input_reference=https://apidoc.cometapi.com/images/image/gemini/6100640_569420.png' ``` ## Set the first and last frames Send `first_frame` to set the opening image. To also set the closing image, include `last_frame` and describe the motion between the two frames in `prompt`. For an opening frame alone, omit `last_frame`. A closing frame requires both `first_frame` and `last_frame`. Each field accepts one publicly accessible HTTPS URL or one PNG or JPEG file. Send each field once, using either a URL or a file. Keep each file at or below 20 MiB (20 × 1024 × 1024 bytes). The frame examples at the top of this page show URL inputs and file uploads, with `seconds` and `size` set explicitly. ## Set duration and size Set `seconds` explicitly to an integer from `5` through `20`. 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. For text-to-video, encoded dimensions can be adjusted for codec alignment. For image-to-video, the reference image can also determine the final framing and aspect ratio. ## Task flow **1. Create the task** Send the multipart form request and store the returned `id`. **2. Poll the task** Call [Retrieve a Flux 3 video](./retrieve) until `status` is `completed` or `failed`. **3. Download the result** 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 **1. Create the task first** Start with [Create a Flux 3 video](./create) and store the returned `id`. **2. Retrieve the task state** Send the task ID to this endpoint until `status` is `completed` or `failed`. **3. Download the MP4 file** 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. Create a HappyHorse video from text, reference images, or an opening frame. The API returns a task ID immediately. Store the returned `id` to poll the task and download the completed video. `POST /v1/videos` uses `multipart/form-data`. Send controls as form fields and reference images as `input_reference` fields, with one HTTPS URL or uploaded image file per field. ## 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`, 1–9 `input_reference` URLs or files | `seconds`, `size` | | First-frame image-to-video | `happyhorse-1.0`, `happyhorse-1.1` | `model`, `prompt`, one `first_frame` URL or file | `seconds`, `size` | Reference images guide the subjects and visual details in the video. Send 1–9 publicly accessible HTTPS image URLs or 1–9 image files, repeating `input_reference` once per image in image order. Use only URLs or only files within this field. Send each URL separately rather than joining URLs with commas. For `input_reference`, each reference image must be at or below 10 MB with `happyhorse-1.0`. With `happyhorse-1.1`, each reference image must be at or below 20 MB. These model limits apply to both image URLs and uploaded files. Use JPEG, JPG, PNG, or WEBP images with a shortest side of at least 400 px. The `input_reference` upload limit is 20 MiB (20 × 1024 × 1024 bytes) per file. Uploaded images must also meet the model-specific limit above. The request samples at the top of this page show multiple image URLs for HappyHorse 1.1 and multiple file uploads for both models. To set the opening frame, send `first_frame` once with one publicly accessible HTTPS image URL or one image file. Use this field in a separate request from `input_reference`. ## 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` | Choose an exact `WxH` value for `size` from the table below. For first-frame requests, the image determines the framing and aspect ratio, while `size` selects the output resolution tier. | 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 **1. Create the task** Send the multipart form request and store the returned `id`. **2. Poll the task** Call [Retrieve a HappyHorse video](./retrieve) until `status` is `completed`, `failed`, or `error`. **3. Download the result** 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 **1. Create the task first** Start with [Create a HappyHorse video](./create) and store the returned `id`. **2. Poll by task ID** Send the task ID to this endpoint until `status` reaches `completed`, `failed`, or `error`. **3. Download the MP4 file** 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, 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 a Seedance video](/api/video/seedance/create)** > > Create Seedance video tasks. > **[Create a HappyHorse video](/api/video/happyhorse/create)** > > Create HappyHorse text-to-video jobs. > **[Create a MiniMax H3 video](/api/video/minimax-h3/create)** > > Create MiniMax H3 text-to-video or reference-image video tasks. > **[Create a Flux 3 video](/api/video/flux-3/create)** > > Create Flux 3 text-to-video or image-to-video tasks. > **[Create a Veo 3 video](/api/video/veo3/create)** > > Create Veo video jobs. > **[Create a Wan video](/api/video/wan/create)** > > Create Wan text-to-video or image-to-video jobs. > **[Create an xAI video](/api/video/xai/video-generation)** > > Generate xAI video jobs. > **[Create a Vidu video](/api/video/vidu/create)** > > Create Vidu text-to-video or image-to-video jobs. > **[Create an Omni video (Beta)](/api/video/omni/create)** > > Create beta Omni video jobs. > **[Create a Kling text-to-video task](/api/video/kling/text-to-video)** > > Generate Kling videos from text prompts. > **[Use Runway models](/api/video/runway/overview)** > > Choose a Runway model for image, video, or audio tasks. ## 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. > [!NOTE] > > 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. > [!TIP] > > 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 > [!NOTE] > > 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 > **Missing task ID** > > Store the ID from the create response before returning from your job handler. > **Polling too fast** > > Add delay and backoff between status checks. > **Unsupported duration or size** > > Use the duration and resolution fields documented for the selected video endpoint. > **Missing video\_url** > > Treat `video_url` as optional and fall back to model-specific result fields or the content route when available. > **Callback not received** > > Use polling as the source of truth and verify that your callback URL accepts POST requests. ## Error codes and retry strategy > **400** > > Do not retry until the prompt, files, duration, or size fields are fixed. > **401** > > Do not retry until the API key is present and valid. > **404** > > Check the task ID, base URL, path, and model ID before retrying. > **413** > > Reduce upload size before retrying. > **429** > > Retry with exponential backoff and reduce create or polling concurrency. > **500 or 503** > > Retry task creation with backoff; keep polling existing tasks unless the task reaches a terminal error. > [!TIP] > > 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 > **[Models page](/overview/models)** > > Read how CometAPI exposes model IDs in the docs. > **[Model directory](https://www.cometapi.com/models/)** > > Browse model availability and capabilities. > **[Pricing](https://www.cometapi.com/pricing/)** > > Check pricing before you call a model. # 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 **1. Initialize first** Start with [Initialize Video for Editing](./initialize-video-for-editing) to get a valid `session_id`. **2. Add or refine points** Call this endpoint as you build the region to edit. **3. Preview the area** Use [Preview Selected Video Area](./preview-selected-video-area) before final submission. > [!TIP] > > 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) > [!TIP] > > 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 > [!TIP] > > 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 **1. Initialize the session** Submit the source clip and save the returned `session_id`. **2. Mark selection points** Continue with [Add Video Selection](./add-video-selection) to define the region you want to edit. **3. Submit the final edit task** After selection is ready, continue with [Create Task](./create-task). > [!TIP] > > 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 **1. Initialize the session** Start with [Initialize Video for Editing](./initialize-video-for-editing) and keep the returned `session_id` on the same account. **2. Add selection points** Use [Add Video Selection](./add-video-selection) until the region is close to correct. **3. Preview before generating** Call this endpoint, then continue to [Create Task](./create-task) only after the selection looks right. > [!TIP] > > For the complete parameter reference, see the [Kling API documentation](https://kling.ai/document-api/apiReference/model/multiElements). # 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 or H3-Max video task with text, reference media, or first and last frames through CometAPI Create a MiniMax H3 or H3-Max video from text, reference media, or first and last frames. Store the returned `id` to poll the task and download the completed video. `POST /v1/videos` uses `multipart/form-data`. Send controls as form fields and repeat each reference field once per media input. ## Choose a model Set `model` to one of the following model IDs. Choose a request size from the matching model table in [Set duration and size](#set-duration-and-size). | Model ID | Resolution tiers | | - | - | | `minimax-h3` | `768P`, `2K` | | `minimax-h3-max` | `480P`, `768P` | ## Choose an input mode Both models use the fields below. Set `model` to the model ID that you selected. | Goal | Required fields | Optional fields | | - | - | - | | Text-to-video | `model`, `prompt` | `seconds`, `size` | | Reference images | `model`, `prompt`, one or more `input_reference` URLs or files | `seconds`, `size` | | Reference video URL, data URI, or file | `model`, `prompt`, one or more `reference_videos` fields | `seconds`, `size` | | Reference audio with an image | `model`, `prompt`, `input_reference`, one or more `reference_audios` fields | `seconds`, `size` | | First and last frame URLs | `model`, `prompt`, `first_frame` | `last_frame`, `seconds`, `size` | | Uploaded first and last frames | `model`, `prompt`, `first_frame` file | `last_frame` file, `seconds`, `size` | The H3-Max request samples include text-to-video at both resolution tiers, reference images, combined image/video/audio references, and first and last frames. ## Use reference images Send reference images through `input_reference` as publicly accessible HTTPS URLs or uploaded files. For multiple images, repeat the field in image order, with one URL or file per field. Use all URLs or all files within this field. Send each URL separately rather than combining URLs into a comma-separated value. You can send up to nine PNG or JPEG reference images, whether you use URLs or uploaded files. Keep each uploaded image at or below 20 MiB. In the prompt, describe the visual details that the generated video should preserve. ## Use reference video and audio Send `reference_videos` and `reference_audios` as multipart text values or uploaded files, using the formats below. Repeat each field once per input, using only text values or only files within that field. Do not combine inputs into a comma-separated value. Different fields can use different input types, such as an image URL with an uploaded audio file. To combine image, video, and audio references, send `input_reference`, `reference_videos`, and `reference_audios` in the same request. | Field | Input | Format | | - | - | - | | `reference_videos` | A direct, publicly accessible HTTPS MP4 URL or an uploaded MP4 file | MP4 with H.264 video; an AAC audio track is optional | | `reference_videos` | A complete Base64 data URI in a text field | `data:video/mp4;base64,` | | `reference_audios` | A direct, publicly accessible HTTPS MP3 URL or an uploaded MP3 file | MP3 | Send at most 12 reference inputs in total, including no more than three videos and three audio clips. Each video or audio clip must be 2–15 seconds. The combined video duration and combined audio duration must each be at or below 15 seconds. Pair reference audio with at least one image through `input_reference`. Describe the motion, timing, or sound that the generated video should follow. Keep each uploaded MP4 at or below 50 MiB and each uploaded MP3 at or below 15 MiB. One MiB is 1024 × 1024 bytes. The request samples at the top of this page show MP4 URLs, MP4 data URIs, and MP3 URLs paired with an image. ### Upload a reference video Upload an MP4 file to guide the shot structure and motion: ```bash theme={null} curl \ https://api.cometapi.com/v1/videos \ -H "Authorization: Bearer $COMETAPI_KEY" \ --form-string 'model=minimax-h3' \ --form-string 'prompt=Follow the uploaded reference video shot structure and motion. No text.' \ --form-string 'seconds=5' \ --form-string 'size=1344x768' \ --form 'reference_videos=@/path/to/reference.mp4;type=video/mp4' ``` ### Upload reference audio with an image Pair a reference image URL with an uploaded MP3 file: ```bash theme={null} curl \ https://api.cometapi.com/v1/videos \ -H "Authorization: Bearer $COMETAPI_KEY" \ --form-string 'model=minimax-h3' \ --form-string 'prompt=Animate the reference image and synchronize the motion with the uploaded reference audio. No text.' \ --form-string 'seconds=5' \ --form-string 'size=1344x768' \ --form-string 'input_reference=https://your-image-host/reference.png' \ --form 'reference_audios=@/path/to/reference.mp3;type=audio/mpeg' ``` ## Set the first and last frames Send `first_frame` for the opening image and optionally one `last_frame` for the ending image. Each field accepts one direct, publicly accessible HTTPS PNG URL or one uploaded PNG file. Keep each uploaded PNG at or below 20 MiB (20 × 1024 × 1024 bytes). Do not combine frame fields with reference image, video, or audio fields. Use a separate request for frame-based generation. With frame inputs, `size` selects the resolution tier. The service can normalize the final output dimensions based on the supplied frames. Continue to send `size` in `WxH` form. > [!NOTE] > > Store the returned `id`. Poll the task until `status` is `completed` or > `failed`. When the task is completed, download the video content. ## Set duration and size For both models, set `seconds` to an integer from `5` through `15`. The default is `5` seconds. Choose a resolution and aspect ratio from the table for your model, then send the corresponding **Request size** value as `size` in `WxH` form. For text and reference-media requests, `size` selects the resolution tier and framing aspect ratio. The service can normalize the final output dimensions based on the requested size and supplied reference media. ### Sizes for `minimax-h3` Use these request sizes with `model=minimax-h3`: | Resolution | Aspect ratio | Request 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` | `2544x1456` | | `2K` | `4:3` | `1920x1440` | | `2K` | `1:1` | `1440x1440` | | `2K` | `3:4` | `1440x1920` | | `2K` | `9:16` | `1440x2560` | ### Sizes for `minimax-h3-max` Use these request sizes with `model=minimax-h3-max`: | Resolution | Aspect ratio | Request size | | - | - | - | | `480P` | `21:9` | `1120x480` | | `480P` | `16:9` | `864x480` | | `480P` | `4:3` | `640x480` | | `480P` | `1:1` | `480x480` | | `480P` | `3:4` | `480x640` | | `480P` | `9:16` | `480x864` | | `768P` | `21:9` | `1792x768` | | `768P` | `16:9` | `1360x768` | | `768P` | `4:3` | `1024x768` | | `768P` | `1:1` | `768x768` | | `768P` | `3:4` | `768x1024` | | `768P` | `9:16` | `768x1360` | ## Task flow **1. Create the task** Send the multipart form request and store the returned `id`. **2. Poll the task** Call [Retrieve a MiniMax H3 video](./retrieve) until `status` is `completed` or `failed`. **3. Download the result** 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 **1. Create the task first** Start with [Create a MiniMax H3 video](./create) and store the returned `id`. **2. Retrieve the task state** Send the task ID to this endpoint until `status` is `completed` or `failed`. **3. Download the MP4 file** 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 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 **1. Create the task** Send the request with the content type for the selected input mode and store the returned `id`. **2. Poll the task** Call [Retrieve an Omni video](./retrieve) until `status` is `completed` or `failed`. **3. Download the result** 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 **1. Create the task first** Start with [Create an Omni video](./create) and store the returned `id`. **2. Poll by task ID** Send the task ID to this endpoint until `status` reaches `completed` or `failed`. **3. Download the MP4 file** 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 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 media with a duration and WxH output size. > [!NOTE] > > Set `size` to a `WxH` value from the size table for your model. > [!WARNING] > > 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 Choose a model for your input mode and resolution, then send its exact ID in the `model` field. | Model | Exact model ID | Modes and resolution tiers | Supported `seconds` | | - | - | - | - | | Seedance 2.5 | `seedance-2-5` | Text-to-video, reference media; `480p`, `720p` | `4`-`30` | | Seedance 2.0 | `doubao-seedance-2-0` | Text-to-video, reference media; `480p`, `720p`, `1080p`, `4K` | `4`-`15` | | Seedance 2.0 Fast | `doubao-seedance-2-0-fast` | Text-to-video, reference media; `480p`, `720p` | `4`-`15` | | Seedance 2.0 Mini | `doubao-seedance-2-0-mini` | Text-to-video, reference media; `480p`, `720p` | `4`-`15` | | Seedance 1.5 Pro | `doubao-seedance-1-5-pro` | Text-to-video, image-to-video; `480p`, `720p`, `1080p` | `4`-`12` | | Seedance 1.0 Pro | `doubao-seedance-1-0-pro` | Text-to-video, image-to-video; `480p`, `720p`, `1080p` | `2`-`10` | ## Use reference images Send `POST /v1/videos` as `multipart/form-data`, with reference images in `input_reference`. For multiple images, repeat the field in image order, with one publicly accessible HTTPS image URL or one uploaded image file per field. Use only URLs or only files within this field. Send each URL separately rather than joining URLs with commas. Keep each uploaded image at or below 20 MiB (20 × 1024 × 1024 bytes). Seedance 1.0 Pro and 1.5 Pro use one reference image. Seedance 2.0, Fast, and Mini accept up to 9 reference images. Seedance 2.5 accepts up to 30 reference images. These counts apply to both URLs and uploaded files. In the prompt, assign each image a role, such as the subject, setting, or visual style. Describe the appearance to preserve, the action, and the camera motion. The request samples at the top of this page show image URL inputs and single-image or multiple-image uploads. ### Send reference image URLs Use two image URLs to guide the subject appearance and setting: ```bash theme={null} curl \ https://api.cometapi.com/v1/videos \ -H "Authorization: Bearer $COMETAPI_KEY" \ --form-string 'model=doubao-seedance-2-0' \ --form-string 'prompt=Use the subject in @Image1 and the setting in @Image2. Use a slow camera push-in and natural motion.' \ --form-string 'seconds=5' \ --form-string 'size=1280x720' \ --form-string 'input_reference=https://your-image-host/subject.png' \ --form-string 'input_reference=https://your-image-host/setting.png' ``` ## Use reference video and audio Seedance 2.0, Fast, Mini, and 2.5 accept `reference_videos` and `reference_audios`. Use MP4 files for video references and MP3 files for audio references. Send each as a publicly accessible HTTPS URL or an uploaded file. Pair reference audio with at least one image or video. In the prompt, use `@Image1`, `@Video1`, and `@Audio1` to assign roles to your references. Number references by their order within each media type. You can combine URLs and uploads across different fields. Within each of `input_reference`, `reference_videos`, and `reference_audios`, use either all URLs or all files. For multiple inputs, repeat the field once per input rather than joining URLs with commas. | Model family | Reference images | Reference videos | Reference audio | Total reference inputs | | - | - | - | - | - | | Seedance 2.0, Fast, and Mini | Up to 9 URLs or files in `input_reference` | Up to 3 | Up to 3 | Up to 12 | | Seedance 2.5 | Up to 30 URLs or files in `input_reference` | Up to 10 URLs or 5 files | Up to 10 URLs or 5 files | Up to 50 | Keep each uploaded video at or below 50 MiB and each uploaded audio file at or below 15 MiB. One MiB is 1024 × 1024 bytes. Standard Seedance 2.0 (`doubao-seedance-2-0`) has additional media limits for both URLs and uploaded files. For reference videos, keep the combined duration between 2 and 15 seconds and the total size under 50 MB. Use reference video resolution of approximately 480p (640x640) to 720p (834x1112). For reference audio, keep the combined duration at or below 15 seconds and each file at or below 15 MB. Uploaded media must also meet the per-file upload limits above. ### Send a reference video URL Use the reference video to guide the camera movement and action: ```bash theme={null} curl \ https://api.cometapi.com/v1/videos \ -H "Authorization: Bearer $COMETAPI_KEY" \ --form-string 'model=doubao-seedance-2-0' \ --form-string 'prompt=Follow the camera movement and action in @Video1. Preserve the direction and pace of the motion.' \ --form-string 'seconds=5' \ --form-string 'size=1280x720' \ --form-string 'reference_videos=https://your-media-host/reference.mp4' ``` ### Pair an image URL with audio Animate the reference subject to the rhythm of the reference audio: ```bash theme={null} curl \ https://api.cometapi.com/v1/videos \ -H "Authorization: Bearer $COMETAPI_KEY" \ --form-string 'model=doubao-seedance-2-0' \ --form-string 'prompt=Animate the subject in @Image1 to the rhythm of @Audio1. Preserve the subject appearance and use a fixed camera.' \ --form-string 'seconds=5' \ --form-string 'size=1280x720' \ --form-string 'input_reference=https://your-image-host/subject.png' \ --form-string 'reference_audios=https://your-media-host/reference.mp3' ``` ### Upload reference media with Seedance 2.5 Upload two images, an MP4 video, and an MP3 audio file in one request: ```bash theme={null} curl \ https://api.cometapi.com/v1/videos \ -H "Authorization: Bearer $COMETAPI_KEY" \ --form-string 'model=seedance-2-5' \ --form-string 'prompt=Use the subject in @Image1 and the setting in @Image2. Follow the motion in @Video1 and the rhythm of @Audio1.' \ --form-string 'seconds=5' \ --form-string 'size=1280x720' \ --form 'input_reference=@/path/to/subject.png;type=image/png' \ --form 'input_reference=@/path/to/setting.png;type=image/png' \ --form 'reference_videos=@/path/to/reference.mp4;type=video/mp4' \ --form 'reference_audios=@/path/to/reference.mp3;type=audio/mpeg' ``` ## Duration by model Set `seconds` to an integer form value within your model's range. If you omit it, CometAPI requests a 5-second clip. | 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 For Seedance 2.5, these `WxH` values apply to both text prompts and reference media. | 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 final column groups exact `WxH` values for Seedance 1.5 Pro, standard Seedance 2.0, and Fast. Seedance 2.0 Fast uses only the `480p` and `720p` values in that 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) | > [!WARNING] > > Seedance 2.0 Mini supports `480p` and `720p`. Set `size` to a `WxH` value from the Mini column. # 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 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. Create a Veo 3.1 video from text or an image. The API returns a task ID immediately. Store the returned `id` to poll the task and download the completed video. `POST /v1/videos` uses `multipart/form-data`. Send controls as form fields and an image as an `input_reference` file field. ## 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`, one `input_reference` image file | `seconds`, `size` | To animate an image, upload one file through `input_reference`, using the field once. The image sets the opening frame; `prompt` describes the motion and camera behavior that follow. ## Set duration and size For this OpenAI-compatible route, set the duration with an explicit integer `seconds` value and the output size with `size`. Send both 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 **1. Create the task** Send the multipart form request and store the returned `id`. **2. Poll the task** Use [Veo3 Retrieve](./retrieve) until `status` is `completed`, `failed`, or `error`. **3. Download the result** 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 **1. Create the job first** Start with [Veo3 Async Generation](./create) and save the returned `id`. **2. Poll until the task is terminal** Keep calling this endpoint until the job leaves `queued` or `in_progress` and reaches a finished state. **3. Store the result** 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 or Q4 video task through CometAPI with POST /v1/videos. Use Q3 for text-to-video or image-to-video, and Q4 for image-to-video or reference-to-video. Then poll the task and download the completed MP4 file. Use this endpoint to create a Vidu video task. Vidu Q3 models create text-to-video and image-to-video tasks. `viduq4-preview` creates image-to-video and reference-to-video tasks. 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` fields. ## Choose an input mode | Goal | Model ID | Required fields | Optional fields | | - | - | - | - | | Text-to-video | `viduq3`, `viduq3-turbo` | `model`, `prompt` | `seconds`, `size` | | Image-to-video | `viduq3`, `viduq3-turbo` | `model`, `prompt`, one `input_reference` file | `seconds`, `size` | | Image-to-video | `viduq4-preview` | `model`, `prompt`, one `input_reference` file or HTTPS image URL | `seconds`, `size` | | Reference-to-video | `viduq4-preview` | `model`, `prompt`, 2–12 `input_reference` HTTPS image URLs | `seconds`, `size`, `reference_audios` | `viduq4-preview` selects the mode from the request. One reference image without reference audio creates an image-to-video task. Two or more reference images, or one reference image with `reference_audios`, create a reference-to-video task. To confirm that `viduq3` or `viduq3-turbo` is available to your API key, use [List available models](/guides/how-to-list-available-models). ## Use reference images For Q3 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. For `viduq4-preview` image-to-video, send one image as an uploaded file or as a publicly accessible HTTPS URL in `input_reference`. The video starts from this image and keeps its aspect ratio. For `viduq4-preview` reference-to-video, send 2–12 publicly accessible HTTPS image URLs. Repeat `input_reference` once per image, and send each URL in its own field. Use PNG, JPEG, or WEBP images. In the prompt, refer to reference images by their order in the request: `@1` is the first `input_reference` image, `@2` is the second, and so on. For example: `The pink car from @1 drives across the snowy hill from @2.` ## Add reference audio For `viduq4-preview` reference-to-video, `reference_audios` adds voice references. Send up to 3 publicly accessible HTTPS URLs of MP3 clips, each 3–12 seconds long, and repeat `reference_audios` once per clip. Send at least one `input_reference` image in the same request. ## Set duration and size | Model ID | `seconds` | Default | | - | - | - | | `viduq3-turbo` | integer `1`-`16` | `5` seconds, `1280x720` | | `viduq3` | integer `1`-`16` | `5` seconds, `1280x720` | | `viduq4-preview` | integer `3`-`16` | `5` seconds, `1280x720` | For Q3 models, 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` | For `viduq4-preview`, set `size` to one of the WxH values below. For reference-to-video, `size` sets the frame shape. For image-to-video, the output keeps the aspect ratio of the input image. | Resolution tier | Aspect ratio | `size` (`WxH`) | | - | - | - | | `720p` | `16:9` (default) | `1280x720` | | `720p` | `9:16` | `720x1280` | | `720p` | `1:1` | `960x960` | | `720p` | `4:3` | `1104x816` | | `720p` | `3:4` | `816x1104` | `viduq4-preview` videos include a generated audio track. ## Task flow **1. Create the task** Send the multipart form request and store the returned `id`. **2. Poll the task** Call [Retrieve a Vidu video](./retrieve) until `status` is `completed`, `failed`, or `error`. **3. Download the result** 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 **1. Create the task first** Start with [Create a Vidu video](./create) and store the returned `id`. **2. Poll by task ID** Send the task ID to this endpoint until `status` reaches `completed`, `failed`, or `error`. **3. Download the MP4 file** When `status` is `completed`, call [Retrieve Vidu video content](./retrieve-content). # 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. # 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 video from text, reference media, or first and last frames through CometAPI, then poll the task and download the MP4 file. Create a Wan video from text, reference media, or first and last frames. Store the returned `id` to poll the task and download the completed video. `POST /v1/videos` uses `multipart/form-data`. Send an explicit integer `seconds` value and a `size` in `WxH` form. `wan3.0-prime` uses the same public request fields, media limits, and task flow as `wan3.0`. Set `model` to the exact value `wan3.0-prime` when targeting Prime. Prime supports text-to-video, image-to-video, first and last frame inputs, and combined image, video, and audio references. Reference media and frame inputs must be sent in separate requests. ## Choose an input mode Every mode requires `model` and `prompt`. The available media inputs depend on the model: | Goal | Model IDs | Media fields | | - | - | - | | Text-to-video | `wan2.6`, `wan2.7`, `wan3.0`, `wan3.0-prime` | Omit media fields | | Image-to-video | `wan2.7`, `wan3.0`, `wan3.0-prime` | `input_reference` URLs or uploaded image files | | Reference video | `wan2.6` | `reference_videos` only | | Image and video references | `wan2.7`, `wan3.0`, `wan3.0-prime` | `input_reference` with `reference_videos` | | Image, video, and audio references | `wan3.0`, `wan3.0-prime` | Image/video references with `reference_audios` | | First and last frames | `wan2.7`, `wan3.0`, `wan3.0-prime` | `first_frame`, optionally `last_frame` | To find a Wan model ID that is available to your API key, use [List available models](/guides/how-to-list-available-models). ## Create a Wan 3.0 Prime video This minimal request creates a five-second text-to-video task with Prime: ```bash Wan 3.0 Prime text-to-video theme={null} prompt='A small robot walks through a bright greenhouse ' prompt+='with smooth camera movement.' curl \ https://api.cometapi.com/v1/videos \ -H "Authorization: Bearer $COMETAPI_KEY" \ -F 'model=wan3.0-prime' \ --form-string "prompt=$prompt" \ -F 'seconds=5' \ -F 'size=1920x1080' ``` ## Use reference images For `wan2.7`, `wan3.0`, and `wan3.0-prime`, send reference images through `input_reference` as publicly accessible HTTPS URLs or uploaded files. For multiple images, repeat the field in image order, with one URL or file per field. Use all URLs or all files within `input_reference`. Send each URL separately rather than combining URLs into a comma-separated value. Use PNG or JPEG images up to 20 MB each. A single `input_reference` URL or file uses the image-to-video workflow. The image guides composition and appearance; use the prompt to describe motion and camera behavior. For `wan3.0` and `wan3.0-prime`, send at most 10 reference images through `input_reference`, whether you use URLs or uploaded files. ## Use reference videos and audio Send videos through `reference_videos` and audio clips through `reference_audios`, repeating each field once per input. Each input can be a publicly accessible HTTPS URL or an uploaded file. Use MP4 files with H.264-encoded video for video references. Use separate MP3 files for audio references. Different fields can use different input types, such as an image URL with uploaded videos. Within `reference_videos` or `reference_audios`, use either all URLs or all files. You can upload up to five video files, each at most 50 MiB (50 × 1024 × 1024 bytes). You can upload up to five audio files, each at most 15 MiB (15 × 1024 × 1024 bytes). ### Wan 2.6 video references Send one to three `reference_videos`, each 2–30 seconds, up to 30 MB, and at least 16 fps. These limits apply to both URLs and uploaded videos. In the prompt, refer to subjects as `@Video1`, `@Video2`, and `@Video3` in input order. For this mode, omit `input_reference`, `reference_audios`, `first_frame`, and `last_frame`. Set `seconds` to `5` or `10`. These examples create a five-second video from two video references. Replace the media URLs or filenames with your inputs: ```bash Wan 2.6 reference video URLs theme={null} curl https://api.cometapi.com/v1/videos \ -H "Authorization: Bearer $COMETAPI_KEY" \ -F 'model=wan2.6' \ --form-string 'prompt=Keep @Video1 and @Video2 recognizable as they walk.' \ -F 'seconds=5' \ -F 'size=1280x720' \ -F 'reference_videos=https://your-media-host/reference-1.mp4' \ -F 'reference_videos=https://your-media-host/reference-2.mp4' ``` ```bash Wan 2.6 uploaded reference videos theme={null} curl https://api.cometapi.com/v1/videos \ -H "Authorization: Bearer $COMETAPI_KEY" \ -F 'model=wan2.6' \ --form-string 'prompt=Keep @Video1 and @Video2 recognizable as they walk.' \ -F 'seconds=5' \ -F 'size=1280x720' \ -F 'reference_videos=@reference-1.mp4;type=video/mp4' \ -F 'reference_videos=@reference-2.mp4;type=video/mp4' ``` ### Wan 2.7 image and video references Combine image and video references to guide subject appearance and motion. Set `seconds` to an integer from `2` through `10`. Omit `reference_audios`. Use two image URLs or two uploaded images with a video reference: ```bash Wan 2.7 image and video URLs theme={null} curl \ https://api.cometapi.com/v1/videos \ -H "Authorization: Bearer $COMETAPI_KEY" \ -F 'model=wan2.7' \ -F 'prompt=Preserve the image subjects and follow the video motion.' \ -F 'seconds=5' \ -F 'size=1280x720' \ -F 'input_reference=https://your-image-host/reference-1.png' \ -F 'input_reference=https://your-image-host/reference-2.jpg' \ -F 'reference_videos=https://your-media-host/reference.mp4' ``` ```bash Wan 2.7 uploaded images and video theme={null} curl https://api.cometapi.com/v1/videos \ -H "Authorization: Bearer $COMETAPI_KEY" \ -F 'model=wan2.7' \ -F 'prompt=Preserve the image subjects and follow the video motion.' \ -F 'seconds=5' \ -F 'size=1280x720' \ -F 'input_reference=@reference-1.png;type=image/png' \ -F 'input_reference=@reference-2.jpg;type=image/jpeg' \ -F 'reference_videos=@reference.mp4;type=video/mp4' ``` ### Wan 3.0 image, video, and audio references For `wan3.0` and `wan3.0-prime`, combine image and video references with audio references to guide appearance, motion, and rhythm. Send at most five video references with a combined duration of at most 15 seconds. Each video must be at least 16 fps. Send at most five audio references with a combined duration of at most 15 seconds. Count video and audio duration separately. Set output `seconds` to an integer from `2` through `30`. Use two image URLs or two uploaded images with one video and two audio clips: ```bash Wan 3.0 image, video, and audio URLs theme={null} curl \ https://api.cometapi.com/v1/videos \ -H "Authorization: Bearer $COMETAPI_KEY" \ -F 'model=wan3.0' \ -F 'prompt=Preserve image subjects, video motion, and audio rhythm.' \ -F 'seconds=5' \ -F 'size=1280x720' \ -F 'input_reference=https://your-image-host/reference-1.png' \ -F 'input_reference=https://your-image-host/reference-2.jpg' \ -F 'reference_videos=https://your-media-host/reference.mp4' \ -F 'reference_audios=https://your-media-host/reference-1.mp3' \ -F 'reference_audios=https://your-media-host/reference-2.mp3' ``` ```bash Wan 3.0 Prime image, video, and audio URLs theme={null} curl \ https://api.cometapi.com/v1/videos \ -H "Authorization: Bearer $COMETAPI_KEY" \ -F 'model=wan3.0-prime' \ -F 'prompt=Preserve image subjects, video motion, and audio rhythm.' \ -F 'seconds=5' \ -F 'size=1280x720' \ -F 'input_reference=https://your-image-host/reference-1.png' \ -F 'input_reference=https://your-image-host/reference-2.jpg' \ -F 'reference_videos=https://your-media-host/reference.mp4' \ -F 'reference_audios=https://your-media-host/reference-1.mp3' \ -F 'reference_audios=https://your-media-host/reference-2.mp3' ``` ```bash Wan 3.0 uploaded images, video, and audio theme={null} curl https://api.cometapi.com/v1/videos \ -H "Authorization: Bearer $COMETAPI_KEY" \ -F 'model=wan3.0' \ -F 'prompt=Preserve image subjects, video motion, and audio rhythm.' \ -F 'seconds=5' \ -F 'size=1280x720' \ -F 'input_reference=@reference-1.png;type=image/png' \ -F 'input_reference=@reference-2.jpg;type=image/jpeg' \ -F 'reference_videos=@reference.mp4;type=video/mp4' \ -F 'reference_audios=@reference-1.mp3;type=audio/mpeg' \ -F 'reference_audios=@reference-2.mp3;type=audio/mpeg' ``` ## Use first and last frames For `wan2.7`, `wan3.0`, and `wan3.0-prime`, send `first_frame` for the opening image and optionally `last_frame` for the ending image. Each field accepts one publicly accessible HTTPS PNG or JPEG URL or one uploaded PNG or JPEG file. For Wan 2.7 frame inputs, the opening image determines the aspect ratio, while `size` selects the output resolution tier. Submit frame inputs in a separate request from `input_reference`, `reference_videos`, and `reference_audios`. These Wan 2.7 examples create a transition between opening and ending frames: ```bash Wan 2.7 first and last frame URLs theme={null} curl https://api.cometapi.com/v1/videos \ -H "Authorization: Bearer $COMETAPI_KEY" \ -F 'model=wan2.7' \ -F 'prompt=Move smoothly from the opening frame to the ending frame.' \ -F 'seconds=5' \ -F 'size=1280x720' \ -F 'first_frame=https://your-image-host/first-frame.png' \ -F 'last_frame=https://your-image-host/last-frame.jpg' ``` ```bash Wan 2.7 uploaded first and last frames theme={null} curl https://api.cometapi.com/v1/videos \ -H "Authorization: Bearer $COMETAPI_KEY" \ -F 'model=wan2.7' \ -F 'prompt=Move smoothly from the opening frame to the ending frame.' \ -F 'seconds=5' \ -F 'size=1280x720' \ -F 'first_frame=@first-frame.png;type=image/png' \ -F 'last_frame=@last-frame.jpg;type=image/jpeg' ``` These Wan 3.0 and Wan 3.0 Prime examples create a transition between opening and ending frames: ```bash Wan 3.0 first and last frame URLs theme={null} curl https://api.cometapi.com/v1/videos \ -H "Authorization: Bearer $COMETAPI_KEY" \ -F 'model=wan3.0' \ -F 'prompt=Move smoothly from the opening frame to the ending frame.' \ -F 'seconds=5' \ -F 'size=1280x720' \ -F 'first_frame=https://your-image-host/first-frame.png' \ -F 'last_frame=https://your-image-host/last-frame.jpg' ``` ```bash Wan 3.0 Prime first and last frame URLs theme={null} curl \ https://api.cometapi.com/v1/videos \ -H "Authorization: Bearer $COMETAPI_KEY" \ -F 'model=wan3.0-prime' \ -F 'prompt=Move smoothly from the opening frame to the ending frame.' \ -F 'seconds=5' \ -F 'size=1280x720' \ -F 'first_frame=https://your-image-host/first-frame.png' \ -F 'last_frame=https://your-image-host/last-frame.jpg' ``` ```bash Wan 3.0 uploaded first and last frames theme={null} curl https://api.cometapi.com/v1/videos \ -H "Authorization: Bearer $COMETAPI_KEY" \ -F 'model=wan3.0' \ -F 'prompt=Move smoothly from the opening frame to the ending frame.' \ -F 'seconds=5' \ -F 'size=1280x720' \ -F 'first_frame=@first-frame.png;type=image/png' \ -F 'last_frame=@last-frame.jpg;type=image/jpeg' ``` ## Set duration and size Send `seconds` as a whole number within the range for your model and input mode. | Model ID | Input mode | `seconds` | Default | | - | - | - | - | | `wan3.0`, `wan3.0-prime` | Text, references, or frames | integer `2`–`30` | `5` seconds, `1920x1080` | | `wan2.7` | Text | integer `2`–`15` | `5` seconds, `1920x1080` | | `wan2.7` | Frames | integer `2`–`15` | `5` seconds, `1080p` tier; aspect ratio follows the opening image | | `wan2.7` | Image/video references | integer `2`–`10` | `5` seconds, `1920x1080` | | `wan2.6` | Text | `5`, `10`, `15` | `5` seconds, `1920x1080` | | `wan2.6` | Video references | `5`, `10` | `5` seconds, `1920x1080` | Set `size` to one of the WxH values below for the target model. The Wan 3.0 size values also apply to `wan3.0-prime`. ### Wan 3.0 size values | Resolution tier | Aspect ratio | `size` (`WxH`) | | - | - | - | | `480p` | `16:9` | `832x480` | | | `9:16` | `480x832` | | | `1:1` | `624x624` | | | `4:3` | `704x528` | | | `3:4` | `528x704` | | `720p` | `16:9` | `1280x720` | | | `9:16` | `720x1280` | | | `1:1` | `960x960` | | | `4:3` | `1088x832` | | | `3:4` | `832x1088` | | `1080p` | `16:9` | `1920x1080` | | | `9:16` | `1080x1920` | | | `1:1` | `1440x1440` | | | `4:3` | `1632x1248` | | | `3:4` | `1248x1632` | ### 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 **1. Create the task** Send the multipart form request and store the returned `id`. **2. Poll the task** Call [Retrieve a Wan video](./retrieve) until `status` is `completed`, `failed`, or `error`. **3. Download the result** 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 **1. Create the task first** Start with [Create a Wan video](./create) and store the returned `id`. **2. Poll by task ID** Send the task ID to this endpoint until `status` reaches `completed`, `failed`, or `error`. **3. Download the MP4 file** 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 while it is `pending`, and stop on `done`, `failed`, or `expired` * `progress` for completion percentage when it is returned * `video.url` when the render is complete ## Polling loop **1. Create or edit the video first** Start with [Create an xAI video](./video-generation) or [Create an xAI video edit](./video-edit), then copy the returned `request_id`. **2. Poll until the task reaches a terminal state** If the response only echoes `request_id`, wait a few seconds and poll again. Continue while `status` is `pending`; stop on `done`, `failed`, or `expired`. **3. Persist the finished file** 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 **1. Submit the edit request** Send the source video URL, edit prompt, and `model: grok-imagine-video`. **2. Poll for the final result** Call [Get xAI video results](./get-video-generation-results) until the job is finished. **3. Store the edited asset** 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 a video with Grok Source: https://apidoc.cometapi.com/api/video/xai/video-generation api/openapi/video/xai/post-video-generation.openapi.json POST /grok/v1/videos/generations Create asynchronous Grok Imagine Video 1.5 jobs from text, a source image, or image and preset-voice references. Use this endpoint to start a Grok video job from text, a source image, or reference inputs. It returns a `request_id` immediately, so treat it as the first step in an async workflow. Always send `model: grok-imagine-video-1.5` explicitly. `model` and `prompt` are required for the 1.5 request shapes documented here. ## Choose an input mode | Mode | Request fields | Rules | | - | - | - | | Text-to-video | `prompt` | Omit `image`, `reference_images`, and `reference_audios`. | | Image-to-video | `prompt`, `image.url` | `image.url` accepts a public image URL or an image data URI. Do not combine `image` with reference inputs. | | Reference-to-video | `prompt` and at least one of `reference_images` or `reference_audios` | Send up to 7 reference images and up to 3 preset voices. Reference-to-video output is limited to `720p`. | For a data URI, use `data:image/png;base64,`. Each `reference_images` item uses the same `url` field. A reference audio item uses a preset `voice_id`, such as `eve`. In the prompt, tags such as `` and `` can identify the corresponding reference. ## Start with a small request * Use `model: grok-imagine-video-1.5` * For a first request, keep `duration` at `1` and `resolution` at `480p` * Keep `prompt` explicit so the scene and motion are clear * Add one input mode at a time before combining reference images and voices ## 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` | `480p` | Higher resolution requests cost more and take longer to complete. Reference-to-video supports up to `720p`. | | `aspect_ratio` | `1:1`, `16:9`, `9:16`, `4:3`, `3:4`, `3:2`, `2:3` | `16:9` for text-to-video | For image-to-video, omission preserves the source image's aspect ratio. | Generated videos include an audio track. Set `duration`, `resolution`, and `aspect_ratio` explicitly when your application depends on a particular output shape. ## Task flow **1. Create the job** Send the model, prompt, and any inputs, then save the returned `request_id`. **2. Poll for completion** Call [Get xAI video results](./get-video-generation-results) until the top-level `status` becomes `done`, `failed`, or `expired`. An initial response can contain only the echoed `request_id` while task metadata is prepared. **3. Persist the output** Copy the final `video.url` into your own storage if you need it after the 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. > [!WARNING] > > 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 > [!WARNING] > > 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. > **Model fallback inside CometAPI** > > Keep the same CometAPI API key and base URL. Try a compatible secondary > model ID after the primary model fails. > **Official-provider fallback** > > 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. > [!WARNING] > > 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. **OpenAI models** 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). **Claude models** 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/seedance/create) * [Retrieve video](/api/video/seedance/query) * [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 > **[Quick Start](/overview/quick-start)** > > Get your free API key and make your first call in minutes. > **[Model List](/overview/models)** > > Browse all 500+ models with live pricing. > **[API Dashboard](https://www.cometapi.com/console)** > > Manage API keys, monitor usage, and track costs. ## Explore by model type > **[Text & LLM](/api/text/chat)** > > **GPT, Claude, Gemini, Grok** and more — through a single chat completions endpoint. Fully OpenAI-compatible; change one line of config. > **[Image Generation](/api/image/openai/images)** > > **Nano Banana, GPT Image, Seedream** and more. Control style, lighting, and character consistency across all major providers. > **[Video Generation](/api/video/seedance/create)** > > **Seedance, HappyHorse, Veo, Grok, Kling** in one place. Text-to-video, image-to-video, and video extension through a unified API. > **[Audio & Speech](/api/audio/create-speech)** > > **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!"}] }' ``` > [!TIP] > > Already using the OpenAI SDK? Only `base_url` and `api_key` need to change — your existing application code works without modification. ## Why CometAPI > **500+ Models, One Key** > > GPT, Claude, Gemini, Nano Banana, Kling, Veo, and hundreds more — accessed with a single API key and a unified endpoint. > **Pay-as-you-go pricing** > > No monthly fees. Pay only for what you use, with competitive rates across all model categories. > **OpenAI Compatible** > > Drop-in replacement for the OpenAI SDK. Point to `https://api.cometapi.com/v1` and keep everything else unchanged. > **Usage Analytics** > > Real-time dashboards for request counts, token usage, latency, and per-model cost breakdown. > **Enterprise Ready** > > Enterprise-grade security, data privacy, and SLA-backed uptime for production workloads. > **Human Support** > > 1:1 support from real engineers for integration help, model selection, and performance tuning. ## More resources > **[Important Notes](/overview/important-guidelines)** > > Rate limits, behavioral differences, and key constraints to know before building. > **[Integration Guides](/integrations/index)** > > Connect CometAPI to Dify, LobeChat, Open WebUI, and 40+ popular AI tools. > **[Error Reference](/errors/error-codes-handling)** > > 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. > [!WARNING] > > 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. > [!NOTE] > > 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 **1. Configure credentials** 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. **2. Chat with a model** 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. **3. Browse models** 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 ``` **4. Inspect one model** 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 ``` **5. Run a multi-protocol request** 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. **1. Sign in or create an account** 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](https://mintcdn.com/cometapi/BtE3Lagaukxd3efj/images/overview/cometapi-console-login.png?fit=max\&auto=format\&n=BtE3Lagaukxd3efj\&q=85\&s=988bee0055bf1ce2552a8d877a48a97d) **2. Open API keys** 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. **3. Create an API key** 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](https://mintcdn.com/cometapi/SZhlxZhCnMLn__BW/images/overview/810968_364191.png?fit=max\&auto=format\&n=SZhlxZhCnMLn__BW\&q=85\&s=aef81a83f29f8eb16655ed4060425f50) **4. Copy the API key** 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](https://mintcdn.com/cometapi/HhtmQffktazbxUvS/images/overview/810968_364193.png?fit=max\&auto=format\&n=HhtmQffktazbxUvS\&q=85\&s=d893f659267150d0faf45f99eb5dffc1) 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/seedance/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/seedance/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 > **How do I create a CometAPI account?** > > 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. > **How do I get a CometAPI API key?** > > 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. > **Where should I store my 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. > **What is the CometAPI base URL for API calls?** > > Use `https://api.cometapi.com/v1` for OpenAI-compatible SDKs and endpoints such as `/v1/chat/completions`. > **Does CometAPI work with the OpenAI Python SDK?** > > Yes. Create an `OpenAI` client, set `api_key` to your CometAPI API key, and set `base_url` to `https://api.cometapi.com/v1`. > **How do I switch from OpenAI to CometAPI?** > > 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). > **Which model ID should I use first?** > > 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. > **Which programming languages does CometAPI support?** > > 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. > **Does CometAPI offer a free trial or free API key?** > > 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. > [!TIP] > > 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`. For a synchronous request, send `"async": false` and read `result.sample` from the create response. See [Generate synchronously](#generate-synchronously) for complete examples. ## 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"); ``` ## Generate synchronously To receive the finished image in the create response, send the JSON boolean `false` in `async`. A successful response has `status: "Ready"` and an image URL in `result.sample`. Use `true` or omit `async` to use the asynchronous workflow above. Do not send `"false"` as a string, or combine `async: false` with `webhook_url` or `webhook_secret`. These examples wait up to 300 seconds for the create response, then download the image. The timeout is a client setting, not a completion deadline: ```bash cURL theme={null} set -e RESULT=$(curl \ https://api.cometapi.com/flux/v1/flux-2-pro \ --max-time 300 \ --fail-with-body \ --silent \ --show-error \ -H "Authorization: Bearer $COMETAPI_KEY" \ -H "Content-Type: application/json" \ -d '{ "prompt": "A red ceramic teapot on a pale blue table, soft window light.", "width": 1280, "height": 768, "output_format": "png", "seed": 424242, "async": false }') if [ "$(printf '%s' "$RESULT" | jq -r '.status')" != "Ready" ]; then echo "FLUX generation did not return a Ready result" >&2 exit 1 fi IMAGE_URL=$(printf '%s' "$RESULT" | jq -er '.result.sample') curl \ "$IMAGE_URL" \ --max-time 60 \ --fail \ --location \ --output flux-result.png ``` ```python Python theme={null} import os from pathlib import Path import requests response = requests.post( "https://api.cometapi.com/flux/v1/flux-2-pro", headers={ "Authorization": "Bearer " + os.environ["COMETAPI_KEY"], "Content-Type": "application/json", }, json={ "prompt": "A red ceramic teapot on a pale blue table, soft window light.", "width": 1280, "height": 768, "output_format": "png", "seed": 424242, "async": False, }, timeout=300, ) response.raise_for_status() task = response.json() if task.get("status") != "Ready": raise RuntimeError("FLUX generation did not return a Ready result") image_response = requests.get(task["result"]["sample"], timeout=60) image_response.raise_for_status() Path("flux-result.png").write_bytes(image_response.content) ``` ```javascript Node.js theme={null} import fs from "node:fs/promises"; const response = await fetch( "https://api.cometapi.com/flux/v1/flux-2-pro", { method: "POST", headers: { Authorization: `Bearer ${process.env.COMETAPI_KEY}`, "Content-Type": "application/json", }, signal: AbortSignal.timeout(300_000), body: JSON.stringify({ prompt: "A red ceramic teapot on a pale blue table, soft window light.", width: 1280, height: 768, output_format: "png", seed: 424242, async: false, }), }, ); if (!response.ok) throw new Error(await response.text()); const task = await response.json(); if (task.status !== "Ready") { throw new Error("FLUX generation did not return a Ready result"); } const imageResponse = await fetch(task.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()), ); ``` ## How the flow works With `async: true` or no `async` field, the create endpoint returns a top-level task `id` while generation continues. 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. With `async: false`, the successful create response contains `status: "Ready"` and `result.sample`. Read the image URL directly without polling. 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. | | `async` | Optional JSON boolean. `false` waits for the image in the create response; `true` or omission submits an asynchronous task. Do not combine `false` with `webhook_url` or `webhook_secret`. | | `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 > **The task stays in a processing state** > > 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. > **The image URL no longer works** > > Download `result.sample` promptly after the task becomes `Ready`, then place the image in storage that your application controls. > **A request field has no effect** > > Use the [Generate a FLUX image API reference](/api/image/flux/flux-generate-image) to choose the request fields for your model. Check field names and JSON types against the request example. ## 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. Available models include `gemini-nano-banana-2.1`, `gemini-3.1-flash-image-preview`, and other Nano Banana model families. ## API key, base URL, authentication Use the Gemini image route through CometAPI. Replace the model ID with your chosen model: ```text theme={null} https://api.cometapi.com/v1beta/models/{model-id}:generateContent ``` For example, with `gemini-nano-banana-2.1`: ```text theme={null} https://api.cometapi.com/v1beta/models/gemini-nano-banana-2.1: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. These examples use `gemini-nano-banana-2.1`. ```bash cURL theme={null} curl -s -X POST \ "https://api.cometapi.com/v1beta/models/gemini-nano-banana-2.1: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-nano-banana-2.1: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-nano-banana-2.1: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 > **The response contains thought images** > > Do not save parts where `thought` is `true`. These are intermediate images, not the final output. > **The request returns text only** > > Check that `generationConfig.responseModalities` includes `IMAGE`, and that the selected model supports image output. > **I need image-to-image** > > 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 > **The saved file does not open** > > Confirm you decoded `b64_json` as base64 bytes and saved the file extension that matches `output_format`. > **The model rejects a parameter** > > Image parameters vary by model. Start with the minimal reference example, then add one optional field at a time. > **The response has no URL** > > 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 > **[OpenAI-compatible API](/quickstarts/text/openai-compatible-api)** > > Use the OpenAI API-compatible Chat Completions route with a CometAPI model ID. > **[Claude API](/quickstarts/text/claude-api)** > > Send Anthropic-compatible Messages requests to Claude models through CometAPI. > **[Gemini API](/quickstarts/text/gemini-api)** > > Start with Gemini native `generateContent`, or use OpenAI-compatible Chat Completions for existing SDK apps. ## Image APIs > **[GPT Image API](/quickstarts/image/gpt-image-api)** > > Generate an image, decode `b64_json`, and save the result. > **[Gemini image API](/quickstarts/image/gemini-image-api)** > > Generate images with Gemini image models, including Nano Banana model families. > **[Flux API](/quickstarts/image/flux-api)** > > Create a Flux image task, poll for the result, and download it before the URL expires. ## Video APIs > **[Veo 3 API](/quickstarts/video/veo-3-api)** > > Create a Veo video task with multipart form data and poll until completion. > **[Kling API](/quickstarts/video/kling-api)** > > Submit a Kling text-to-video task and track it through polling or callbacks. ## Supporting guides > **[Models](/overview/models)** > > Find available model IDs and route each model to the correct API page. > **[Use OpenAI SDKs](/guides/use-cometapi-with-openai-sdk)** > > Configure OpenAI-compatible SDK clients with the CometAPI base URL. > **[Estimate cost](/guides/how-to-estimate-cost-before-calling-a-model)** > > Plan budget guards before token, image, or video requests. > **[Use webhooks and polling](/guides/webhook-and-polling-for-video-generation)** > > 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 > **The request returns 401** > > 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. > **The SDK still calls Anthropic directly** > > Confirm that the SDK client sets `base_url` in Python or `baseURL` in Node.js to `https://api.cometapi.com`. > **Which model should I use** > > 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 > **Which path should I start with** > > 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. > **Native Gemini fields fail on Chat Completions** > > Send `contents`, `parts`, `generationConfig`, and `streamGenerateContent` requests to the Gemini native endpoint. The OpenAI-compatible route expects `messages` and Chat Completions parameters. > **The Gemini model ID fails** > > 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. > **The SDK points to the wrong service** > > 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 > **Is this the OpenAI API?** > > No. This is CometAPI's OpenAI-compatible API route. You use a CometAPI API key, the CometAPI base URL, and a CometAPI model ID. > **The request returns 401** > > 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. > **The model is not found** > > Use a CometAPI model ID that supports text or chat requests. Check the Models page before retrying. > **The SDK still calls OpenAI** > > 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 > **The response shape is different from OpenAI video routes** > > 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. > **The task never reaches succeed** > > Use bounded polling and inspect `data.task_status_msg` when a task fails. Store the task ID for later diagnostics. > **Should I use callback\_url or polling** > > 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). # 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 > **The request fails with a content type problem** > > Send multipart form data. Do not send Veo create requests as JSON. > **Polling takes longer than expected** > > Use a bounded polling loop, store the task ID, and surface a pending state in your application instead of blocking a web request. > **How should I control cost** > > 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**: * **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. * **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+ USD** or **stable daily consumption of over 100 USD**, 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. # 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). *** # 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. > [!NOTE] > > 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. **1. Open Workspace settings** Open [Workspace settings](https://www.cometapi.com/console/workspace/setting), then select the Workspace that you want to manage. **2. Start an invitation** In the member list, select **Invite Member**. **3. Send the invitation** Enter the person's email address, then send the invitation. **4. Accept 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. > [!WARNING] > > 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 > **What is a CometAPI Workspace?** > > A CometAPI Workspace is a team membership area inside an Organization. Workspace roles control who can view and manage the member list. > **How is a Workspace different from an Organization?** > > 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. > **Who can invite or remove Workspace members?** > > A Workspace Owner or Workspace Admin can invite members, cancel pending invitations, and remove other members. All Workspace roles can view the member list. > **How long is a Workspace invitation valid?** > > A Workspace invitation expires 24 hours after it is created. > **Which role does an invited person receive?** > > A person who accepts a Workspace invitation joins with the Workspace Member role. > **Can a Workspace Admin manage Credits?** > > No. A Workspace Admin can manage Workspace members, but Credits permissions require the Organization Owner role. > **Who can add Credits or configure Auto Top-Up?** > > Only the Organization Owner can add Credits, configure Auto Top-Up, and redeem a redemption code for the Organization. > **What happens when I remove a Workspace member?** > > 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. > [!NOTE] > > Generate a personal access token with the `api_key:write` permission at [Console → Personal Settings](https://www.cometapi.com/console/personal). Send the token as the raw `Authorization` header value. Do not prefix it with `Bearer`. The successful response includes the created API key record in `data`, with its numeric ID in `data.id` and complete API key in `data.key`. > [!WARNING] > > Save `data.key` immediately. Subsequent list, detail, and update responses contain masked API keys that cannot authenticate model requests. For model requests, use the returned `data.key` unchanged as `Authorization: Bearer `. Do not add an `sk-` prefix. If you did not save the complete API key, open [Console → API Keys](https://www.cometapi.com/console/token). Find the API key that you created, select **Copy**, and complete identity verification. ## Creation response | Field | Type | Description | | - | - | - | | `success` | boolean | Whether the API key was created. | | `message` | string | Status message. Empty on success. | | `data` | object | Created API key record, including its settings and quota. Present on success. | | `data.id` | integer | Numeric API key ID. Use this ID to retrieve, update, or delete the record. | | `data.key` | string | Complete API key returned during creation. Save this value for model requests. | ## 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. > [!NOTE] > > 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. > [!NOTE] > > Generate a personal access token with the `api_key:read` permission at [Console → Personal Settings](https://www.cometapi.com/console/personal). Send the token as the raw `Authorization` header value. Do not prefix it with `Bearer`. For security, the `key` field contains a masked API key that cannot authenticate model requests. Save the complete API key from `data.key` when you [create an API key](./create-api-key). If you did not save it, open [Console → API Keys](https://www.cometapi.com/console/token). Find an API key that you created, select **Copy**, and complete identity verification. The `id` path parameter is the numeric API key ID returned by [Create an API key](./create-api-key) or [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 | Masked API key for identification. This value cannot authenticate model requests. Copy the complete API key from [Console → API Keys](https://www.cometapi.com/console/token) after identity verification. | | `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. > [!NOTE] > > 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. > [!NOTE] > > Generate a personal access token with the `api_key:read` permission at [Console → Personal Settings](https://www.cometapi.com/console/personal). Send the token as the raw `Authorization` header value. Do not prefix it with `Bearer`. For security, the `key` field contains a masked API key that cannot authenticate model requests. Save the complete API key from `data.key` when you [create an API key](./create-api-key). If you did not save it, open [Console → API Keys](https://www.cometapi.com/console/token). Find an API key that you created, select **Copy**, and complete identity verification. ## 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 | Masked API key for identification. This value cannot authenticate model requests. Copy the complete API key from [Console → API Keys](https://www.cometapi.com/console/token) after identity verification. | | `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. > [!NOTE] > > Generate a personal access token with the `api_key:write` permission at [Console → Personal Settings](https://www.cometapi.com/console/personal). Send the token as the raw `Authorization` header value. Do not prefix it with `Bearer`. The response includes the updated record with a masked `key` value that cannot authenticate model requests. Save the complete API key from `data.key` when you [create an API key](./create-api-key). If you did not save it, open [Console → API Keys](https://www.cometapi.com/console/token). Find an API key that you created, select **Copy**, and complete identity verification. > [!WARNING] > > 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 [Create an API key](./create-api-key) or [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 > **[Create speech](/api/audio/create-speech)** > > Convert text to speech. > **[Create transcription](/api/audio/create-transcription)** > > Transcribe audio to text. > **[Create translation](/api/audio/create-translation)** > > 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. > [!NOTE] > > 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. > [!TIP] > > 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 > [!NOTE] > > 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 > **Unsupported audio format** > > Use the formats documented on the endpoint page. > **Large upload rejected** > > Compress the audio file or split the job into smaller files. > **Empty transcription** > > Confirm that the file contains speech and that the field name matches the docs. > **Wrong base URL** > > Use `https://api.cometapi.com/v1`. ## Error codes and retry strategy > **400** > > Do not retry until the text, file, model ID, voice, or format is fixed. > **401** > > Do not retry until the API key is present and valid. > **404** > > Check the base URL, path, and model ID before retrying. > **413** > > Reduce upload size before retrying. > **429** > > Retry with exponential backoff and reduce concurrency. > **500 or 503** > > Retry with backoff for transient provider or service errors. > [!TIP] > > 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 > **[Models page](/overview/models)** > > Read how CometAPI exposes model IDs in the docs. > **[Model directory](https://www.cometapi.com/models/)** > > Browse model availability and capabilities. > **[Pricing](https://www.cometapi.com/pricing/)** > > 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. > [!NOTE] > > 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. > [!NOTE] > > 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. > [!TIP] > > 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 > [!NOTE] > > 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 > **Input too long** > > Split long documents into chunks before embedding. > **Wrong model type** > > Choose an embedding-capable model from the model directory. > **Vector dimensions mismatch** > > Keep the same model and dimensions for one vector index. > **Missing API key** > > Send `Authorization: Bearer $COMETAPI_KEY`. ## Error codes and retry strategy > **400** > > Do not retry until the input, model ID, or dimensions setting is fixed. > **401** > > Do not retry until the API key is present and valid. > **404** > > Check the base URL, path, and model ID before retrying. > **429** > > Retry with exponential backoff and reduce batch size or concurrency. > **500 or 503** > > Retry with backoff for transient provider or service errors. > [!TIP] > > 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 > **[Models page](/overview/models)** > > Read how CometAPI exposes model IDs in the docs. > **[Model directory](https://www.cometapi.com/models/)** > > Browse model availability and capabilities. > **[Pricing](https://www.cometapi.com/pricing/)** > > 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. > [!TIP] > > 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. > [!NOTE] > > 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 **1. Create the avatar task** Submit the image and one audio source, then save the returned task id. **2. Poll the task** Continue with [Get a Kling task](./individual-queries) until the task reaches a terminal state. **3. Store the finished result** Copy the final asset into your own storage if you need retention beyond the provider delivery URL. > [!NOTE] > > 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 **1. Identify faces first** Run [Lip-Sync](./lip-sync) on the source video and keep the returned `session_id` plus the target `face_id` values. **2. Create the advanced lip-sync task** Submit `session_id` and the `face_choose` array through this endpoint. **3. Track the generated task** Save the returned task id for status checks and final result retrieval. > [!TIP] > > 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 > [!TIP] > > 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 **1. Submit the image-to-video request** Create the task and store the returned Kling `task_id`. **2. Poll the task** Continue with [Get a Kling task](./individual-queries) to follow task status until output is ready. **3. Store the result** Persist the finished asset if you need retention beyond the provider delivery URL. > [!TIP] > > 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. > [!WARNING] > > 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 **1. Create the task from the matching endpoint** 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). **2. Poll until the task is terminal** 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`. **3. Continue to the next workflow step** 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}` | > [!NOTE] > > 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 > [!TIP] > > For the complete parameter reference, see the [official Kling documentation](https://kling.ai/document-api/apiReference/model/lipSync). # Create a Kling image-to-video task by model Source: https://apidoc.cometapi.com/api/video/kling/model-routes/image-to-video api/openapi/video/kling/model-routes/post-image-to-video.openapi.json POST /image-to-video/{model} Create a Kling video from a source image with a model-specific route, then retrieve the video by task ID. Send a source image to `POST /image-to-video/{model}` to create a video task. You can add a prompt to describe the motion. The response contains an `id` that you use to retrieve the result. ## Choose a model Put the model ID in the URL. Do not add a model field to the JSON body. | Model ID | Resolution | Duration | Audio | | - | - | - | - | | `kling-3.0-turbo` | `720p`, `1080p` | Integer from 3 to 15 seconds | Omit `audio` | | `kling-3.0` | `720p`, `1080p`, `4k` | Integer from 3 to 15 seconds | `native` or `off` | | `kling-2.6` | `720p`, `1080p` | 5 or 10 seconds | `native` or `off`; use `1080p` with `native` | | `kling-2.5-turbo` | `720p`, `1080p` | 5 or 10 seconds | Omit `audio` | `kling-3.0-turbo` accepts a `first_frame` only. `kling-2.5-turbo`, `kling-3.0`, and `kling-2.6` also support a `last_frame`; include a `first_frame` with it. For `kling-2.5-turbo` and `kling-2.6`, the first-and-last-frame combination requires `1080p`. ## Request parameters Put each input in `contents`. A `prompt` entry uses `text`; a frame entry uses `url`. For an image, supply a publicly accessible URL or Base64-encoded JPG or PNG data. | Field | Type | Required | Description | | - | - | - | - | | Path `model` | string | Yes | Model ID in the URL. Choose an ID from the table above; do not add it to the request body. | | `contents` | array | Yes | Input entries. Include a `first_frame` image; add a `prompt` entry or a model-supported `last_frame` image when needed. | | `contents[].type` | string | Yes | `prompt`, `first_frame`, or `last_frame`. Include a `first_frame` when you use `last_frame`; the selected model determines whether `last_frame` is available. | | `contents[].text` | string | For a `prompt` entry | Text that describes the motion. | | `contents[].url` | string | For a frame entry | Public image URL or Base64-encoded JPG or PNG data. | | `settings.resolution` | string | No | Output resolution from the selected model's row above. Defaults to `720p`. | | `settings.duration` | integer | No | Video length in seconds from the selected model's row above. Defaults to `5`. | | `settings.multi_shot` | boolean | No | For `kling-3.0` only, the official default is `true`. Set `true` for multiple shots or `false` for one shot, and set the value explicitly when you use this field. | | `settings.audio` | string | No | For `kling-3.0` or `kling-2.6`, set `native` for generated audio or `off` for no generated audio. Set the value explicitly when you use this field. | | `options.callback_url` | string | No | Public URL that receives task updates. | | `options.external_task_id` | string | No | Your identifier for matching the task to your application. | | `options.watermark_info` | object | No | Watermark configuration for the output. | The following request animates one source image as a five-second video: ```json theme={null} { "contents": [ { "type": "prompt", "text": "The camera slowly moves closer to the scene." }, { "type": "first_frame", "url": "https://raw.githubusercontent.com/ultralytics/yolov5/402e17ddf820996f51a191cbb798376e1144f069/data/images/zidane.jpg" } ], "settings": { "resolution": "720p", "duration": 5 } } ``` Replace the image URL with a public URL or Base64-encoded JPG/PNG for your source image when you use a different image. Send this body to `https://api.cometapi.com/image-to-video/kling-3.0-turbo` with your CometAPI API key. The OpenAPI code panel provides Shell, Python, and JavaScript requests with the same body. ## Retrieve the video The create response has this shape: ```json theme={null} { "code": 0, "message": "SUCCEED", "data": { "id": "example-task-id", "status": "submitted" } } ``` Save `data.id`. Use [Get a Kling task](./tasks) with that ID until the task reaches a terminal status. Read the video URL from the task's `outputs` array. # Create a Kling motion-control video Source: https://apidoc.cometapi.com/api/video/kling/model-routes/motion-control api/openapi/video/kling/model-routes/post-motion-control.openapi.json POST /motion-control/{model} Create a Kling motion-control task from a character image and a reference motion video. Use `POST /motion-control/{model}` to animate a character image with the movement from a reference video. The request creates an asynchronous task. ## Choose a model | Model ID | Resolution | `settings.audio` | | - | - | - | | `kling-3.0` | `720p`, `1080p` | `original`, `off` | | `kling-2.6` | `720p`, `1080p` | `original`, `off` | Use the character image and reference video as publicly accessible URLs. Set `settings.audio` to `original` to retain audio from the reference video, or `off` for silent output. The image must be JPG or PNG, at most 50 MB, and at least 300 pixels on each edge. Use an MP4 or MOV reference video of at least 3 seconds and at most 100 MB. With `character_orientation: image`, the video can be up to 10 seconds; with `video`, it can be up to 30 seconds. ## Request parameters | Field | Required | Description | | - | - | - | | Path `model` | Yes | Model ID in the URL: `kling-3.0` or `kling-2.6`. Do not add it to the request body. | | `contents` | Yes | Array containing one `image` item and one `video` item. Add a `prompt` item to describe the scene. | | `contents[].type` | Yes | `image` for the character, `video` for the motion reference, or `prompt` for text guidance. | | `contents[].url` | For image and video items | Public URL for the character image or reference motion video. | | `contents[].text` | For a `prompt` item | Required text guidance for the generated scene. | | `settings.resolution` | No | Output resolution: `720p` or `1080p`. If omitted, the request uses `720p`. | | `settings.character_orientation` | Yes | `image` uses the character orientation from the image; `video` uses the reference video. | | `settings.audio` | No | Set `original` to retain reference audio or `off` to disable it. Set the value explicitly. | | `options.callback_url` | No | HTTPS URL that receives task status callbacks. | | `options.external_task_id` | No | Your own task identifier for correlation; retain the returned `data.id` for queries. | | `options.watermark_info.enabled` | No | Set to `true` to request a watermark. | To animate a character image, send this request body to `POST /motion-control/kling-2.6`. Replace the media URLs with your own accessible files when using your own character and motion: ```json theme={null} { "contents": [ { "type": "prompt", "text": "The character performs the dance shown in the reference video." }, { "type": "image", "url": "https://p2-kling.klingai.com/kcdn/cdn-kcdn112452/kling-qa-test/multi-3.ng.png" }, { "type": "video", "url": "https://p2-kling.klingai.com/kcdn/cdn-kcdn112452/kling-qa-test/dance.mp4" } ], "settings": { "resolution": "720p", "character_orientation": "video", "audio": "off" } } ``` The response returns an `id` for the asynchronous task: ```json theme={null} { "code": 0, "message": "SUCCEED", "data": { "id": "example-task-id", "status": "submitted" } } ``` Use the `data.id` value with [Get a Kling task](./tasks) until the task completes. Read the finished video URL from the task's `outputs` array. Store the video in your own storage if you need durable access. The OpenAPI panel contains matching Shell, Python, and JavaScript requests. For more input details, see the [Kling motion-control API reference](https://kling.ai/document-api/api/video/3-0-omni/motion-control). # Create a Kling Omni video Source: https://apidoc.cometapi.com/api/video/kling/model-routes/omni-video api/openapi/video/kling/model-routes/post-omni-video.openapi.json POST /omni-video/{model} Create a Kling Omni video task with the model ID in the URL, then retrieve the result by task ID. Use `POST /omni-video/{model}` to create an asynchronous Kling Omni video task. Place the model ID in the URL and provide the input in `contents`. ## Choose a model * `kling-3.0-omni`: `720p`, `1080p`, or `4k`; 3-15 seconds; `native`, `original`, or `off` audio. * `kling-o1`: `720p` or `1080p`; 3-10 seconds; `original` or `off` audio. The text-only example uses `kling-3.0-omni`. To create a silent video, set `settings.audio` to `off`. ## Request parameters | Field | Required | Description | | - | - | - | | Path `model` | Yes | Model ID in the URL. Choose an ID from the list above; do not add it to the request body. | | `contents` | Yes | Nonempty array of video inputs. For a text-only request, include a `prompt` item. | | `contents[].type` | Yes | `prompt`, `first_frame`, `last_frame`, `refer_image`, `feature_video`, or `base_video`. A `last_frame` needs a `first_frame`. | | `contents[].text` | For a `prompt` item | Text that describes the video. | | `contents[].url` | For image or video items | Image URL or Base64 image data; video items use a public video URL. | | `settings.resolution` | No | Output resolution. If omitted, the request uses `720p`. Available values depend on `model`. | | `settings.aspect_ratio` | No | Frame shape: `16:9`, `9:16`, or `1:1`. If omitted, the request uses `16:9`. | | `settings.duration` | No | Video length in whole seconds. If omitted, the request uses 5 seconds. Use a duration within the selected model's range. | | `settings.multi_shot` | No | For `kling-3.0-omni`, set `true` for multiple shots or `false` for one continuous shot. Do not include this field for `kling-o1`. | | `settings.audio` | No | Set `native`, `original`, or `off` according to the selected model and inputs. | | `options.callback_url` | No | HTTPS URL that receives task status callbacks. | | `options.external_task_id` | No | Your own task identifier for correlation; retain the returned `data.id` for queries. | | `options.watermark_info.enabled` | No | Set to `true` to request a watermark. | For `kling-3.0-omni`, a `feature_video` input requires `settings.multi_shot: true` and `settings.audio: off`. A `base_video` input requires `settings.multi_shot: false` and cannot use `settings.audio: native`. Do not combine `base_video` with a first or last frame. The official default for `kling-3.0-omni` is `multi_shot: true`; set the field explicitly when you need a defined shot mode. For `kling-o1`, prompts can contain up to 2500 characters. If the request contains only a `first_frame` and no other reference image or video, use a duration of 5 or 10 seconds. To create a five-second text-only video, send this request body to `POST /omni-video/kling-3.0-omni`: ```json theme={null} { "contents": [ { "type": "prompt", "text": "A paper boat drifts on a pond." } ], "settings": { "resolution": "720p", "aspect_ratio": "16:9", "duration": 5, "multi_shot": false, "audio": "off" } } ``` The response returns an `id` for the asynchronous task: ```json theme={null} { "code": 0, "message": "SUCCEED", "data": { "id": "example-task-id", "status": "submitted" } } ``` Use the `data.id` value with [Get a Kling task](./tasks) until the task completes. Read the finished video URL from the task's `outputs` array. Store the video in your own storage if you need durable access. The OpenAPI panel contains matching Shell, Python, and JavaScript requests. For more input combinations, see the [Kling 3.0 Omni video API reference](https://kling.ai/document-api/api/video/3-0-omni/video-omni) or [Kling O1 Omni video API reference](https://kling.ai/document-api/api/video/o1/video-omni). # Get a Kling model-route task Source: https://apidoc.cometapi.com/api/video/kling/model-routes/tasks api/openapi/video/kling/model-routes/get-tasks.openapi.json GET /tasks Get the status and video output of a Kling model-route task by its task ID. Use this endpoint after a Kling model-route creation request. Save `data.id` from the creation response and pass that ID as `task_ids`. ## Request parameter | Parameter | Required | Description | | - | - | - | | `task_ids` | Yes | Task ID returned by a model-route creation request in `data.id`. | To retrieve one task, replace `` with the `data.id` value from the creation response: ```bash theme={null} task_id="" curl "https://api.cometapi.com/tasks?task_ids=${task_id}" \ -H "Authorization: Bearer $COMETAPI_KEY" ``` Immediately after creation, the response contains the submitted task: ```json theme={null} { "code": 0, "message": "SUCCEED", "data": [ { "id": "", "status": "submitted" } ] } ``` ## Read the result Read the task from `data[0]` and continue querying until its `status` is terminal. When the status is `succeeded`, read the video URL from that task's `outputs` array. Some observed Comet compatibility responses return a bare task object or include a top-level `status`; these are compatibility forms, not the canonical envelope. When `data` is present, use `data[0].status`. A completed task has this response shape: ```json theme={null} { "code": 0, "message": "SUCCEED", "data": [ { "id": "", "status": "succeeded", "outputs": [ { "type": "video", "url": "https://media.example.com/video.mp4", "duration": "5.041" } ] } ] } ``` | Field | Description | | - | - | | `id` | Task ID from the creation response. | | `status` | Current task state. Continue querying until it reaches a terminal state. | | `message` | Task detail returned when available. | | `outputs[].type` | Output media type. Select an item with `type: video`. | | `outputs[].url` | Video URL to download or store when the task succeeds. | | `outputs[].duration` | Video duration in seconds when returned. | Store the finished video in your own storage if you need to retain it beyond the returned URL's availability. # Create a Kling text-to-video task by model Source: https://apidoc.cometapi.com/api/video/kling/model-routes/text-to-video api/openapi/video/kling/model-routes/post-text-to-video.openapi.json POST /text-to-video/{model} Create a Kling video from a text prompt with a model-specific route, then retrieve the video by task ID. Send a prompt to `POST /text-to-video/{model}` to create a video task. The response contains an `id` that you use to retrieve the result. ## Choose a model Put the model ID in the URL. Do not add a model field to the JSON body. | Model ID | Resolution | Duration | Audio | | - | - | - | - | | `kling-3.0-turbo` | `720p`, `1080p` | Integer from 3 to 15 seconds | Omit `audio` | | `kling-3.0` | `720p`, `1080p`, `4k` | Integer from 3 to 15 seconds | `native` or `off` | | `kling-2.6` | `720p`, `1080p` | 5 or 10 seconds | `native` or `off`; use `1080p` with `native` | | `kling-2.5-turbo` | `720p`, `1080p` | 5 or 10 seconds | Omit `audio` | ## Request parameters | Field | Type | Required | Description | | - | - | - | - | | Path `model` | string | Yes | Model ID in the URL. Choose an ID from the table above; do not add it to the request body. | | `prompt` | string | Yes | Description of the video to generate. | | `settings.resolution` | string | No | Output resolution from the selected model's row above. Defaults to `720p`. | | `settings.aspect_ratio` | string | No | Output frame ratio: `16:9`, `9:16`, or `1:1`. Defaults to `16:9`. | | `settings.duration` | integer | No | Video length in seconds from the selected model's row above. Defaults to `5`. | | `settings.multi_shot` | boolean | No | For `kling-3.0` only, the official default is `true`. Set `true` for multiple shots or `false` for one shot, and set the value explicitly when you use this field. | | `settings.audio` | string | No | For `kling-3.0` or `kling-2.6`, set `native` for generated audio or `off` for no generated audio. Set the value explicitly when you use this field. | | `options.callback_url` | string | No | Public URL that receives task updates. | | `options.external_task_id` | string | No | Your identifier for matching the task to your application. | | `options.watermark_info` | object | No | Watermark configuration for the output. | The following request creates a five-second video with `kling-3.0-turbo`: ```json theme={null} { "prompt": "A paper boat drifts across a calm pond at sunrise.", "settings": { "resolution": "720p", "aspect_ratio": "16:9", "duration": 5 } } ``` Send this body to `https://api.cometapi.com/text-to-video/kling-3.0-turbo` with your CometAPI API key. The OpenAPI code panel provides Shell, Python, and JavaScript requests with the same body. ## Retrieve the video The create response has this shape: ```json theme={null} { "code": 0, "message": "SUCCEED", "data": { "id": "example-task-id", "status": "submitted" } } ``` Save `data.id`. Use [Get a Kling task](./tasks) with that ID until the task reaches a terminal status. Read the video URL from the task's `outputs` array. # 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. > [!WARNING] > > 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. > [!NOTE] > > 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 **1. Submit the Motion Control request** 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`. **2. Poll the task** Use [Get a Kling task](./individual-queries) with the returned `task_id`. Continue until the status is `succeed` or `failed`. **3. Store the result** 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`. > [!TIP] > > 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 **1. Submit the multi-image request** Send the image list, prompt, and duration, then save the returned Kling `task_id`. **2. Poll the task** Continue with [Get a Kling task](./individual-queries) until the task reaches a terminal state. **3. Persist the result** Store the finished video if you need retention beyond the provider delivery URL. > [!TIP] > > For the complete parameter reference, see the [official Kling documentation](https://kling.ai/document-api/apiReference/model/multiImageToVideo). # 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 **1. Initialize the editing session** Start with [Initialize Video for Editing](./initialize-video-for-editing) to obtain the `session_id` for the clip you want to edit. **2. Build the selection area** Use [Add Video Selection](./add-video-selection) and, when needed, [Preview Selected Video Area](./preview-selected-video-area) to refine the edit region. **3. Submit the final task** 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 > [!TIP] > > 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 **1. Create the task first** Start with [Create a Kling Omni video](./omni-video) and store the returned `task_id`. **2. Poll until the task is terminal** Keep querying until `data.task_status` reaches `succeed` or `failed`. **3. Use the returned MP4 URL** 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. > [!NOTE] > > 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 **1. Create the Omni task** Submit the request and store the returned `task_id`. **2. Poll the Omni task** Continue with [Get a Kling Omni video](./omni-query) until the task finishes. **3. Persist the finished video** 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 **1. Submit the audio task** Send the text prompt and duration, then save the returned task id. **2. Poll the task** Continue with [Get a Kling task](./individual-queries) using the Kling audio query path until the task reaches a terminal state. **3. Store the audio output** Persist the final audio asset if you need it beyond the provider delivery window. > [!TIP] > > 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 **1. Submit the generation request** Create the task through this endpoint and save the returned Kling task id. **2. Poll the task state** Check progress through [Get a Kling task](./individual-queries) until the task reaches a terminal state. **3. Persist the result** Once Kling returns the finished asset metadata, move the result into your own storage if you need long retention. > [!NOTE] > > 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 **1. Submit the effect request** Send `effect_scene` plus the matching `input` object and store the returned task id. **2. Poll the task** Continue with [Get a Kling task](./individual-queries) until the effect job finishes. **3. Persist the final asset** Download or mirror the finished effect video if you need stable retention. > [!TIP] > > 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 **1. Finish the parent video task** Create the original Kling video and wait until its result is available. **2. Submit the extension request** Send the parent `task_id`, `video_id`, and optional prompt, then save the returned task id. **3. Poll the extension task** Continue with [Get a Kling task](./individual-queries) until the extended video reaches a terminal state. > [!TIP] > > 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 **1. Submit the source video** Send either the Kling `video_id` or an accessible `video_url`, then save the returned task id. **2. Poll the task** Continue with [Get a Kling task](./individual-queries) using the Kling audio query path until the task reaches a terminal state. **3. Persist the output** Store the final audio asset if you need stable retention or downstream processing. > [!TIP] > > For the complete parameter reference, see the [official Kling documentation](https://app.klingai.com/global/dev/document-api/apiReference/model/videoToAudio). # 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 Create a Runway Act-Two character-performance task through CometAPI using a character image or video and a reference performance clip. Use `act_two` to apply a reference video's performance to a character image or video. The request returns a task `id` for retrieving the finished output. ## Prepare the assets * Authenticate with your CometAPI API key. * Set `model` to `act_two`. * Supply `character.type` as `image` or `video`, with the asset in `character.uri`. Keep a recognizable face visible and inside the frame. * Supply `reference.type` as `video`, with a performance clip of 3 to 30 seconds in `reference.uri`. * Replace the example media URLs with accessible HTTPS URLs. Media fields also accept Base64 data URIs with an encoded size of up to 5 MB. ## Configure the performance Only `model`, `character`, and `reference` are required. | Field | How to use it | | - | - | | `bodyControl` | Set `true` to request body movements and gestures in addition to facial expressions. Omit to leave the setting unspecified. | | `expressionIntensity` | Use `1` through `5`; higher values request stronger expressions. Omit for `3`. | | `seed` | Use `1` through `4294967295` for an explicit sampling seed. Omit for a random seed. | | `contentModeration.publicFigureThreshold` | Use `auto` for standard public-figure detection or `low` for less restrictive detection. | `bodyControl: false` is treated as omission, so it does not explicitly disable body control. A `seed` or `expressionIntensity` of `0` is also treated as omission. Omit optional fields instead of sending `null`. Optional `ratio` values are `1280:720`, `720:1280`, `960:960`, `1104:832`, `832:1104`, or `1584:672`. ## Retrieve the result Save the returned `id` and use [Get a Runway task](./runway-to-get-task-details) to retrieve the task status. When `status` is `SUCCEEDED`, read the result URLs from `output`. If the task fails, inspect `failure` and `failureCode` when present. # Convert Runway speech Source: https://apidoc.cometapi.com/api/video/runway/official-format/convert-speech api/openapi/video/runway/official-format/post-convert-speech.openapi.json POST /runwayml/v1/speech_to_speech Convert recorded dialogue into a selected voice with the Runway API. Use `POST /runwayml/v1/speech_to_speech` to convert recorded dialogue into a preset voice. Use the model ID `eleven_multilingual_sts_v2`. Send your CometAPI API key with Bearer authentication and a JSON request body. ## Provide dialogue and a voice | Field | Required value | | - | - | | `model` | `eleven_multilingual_sts_v2` | | `media.type` | `audio` for an audio file or `video` for a video containing dialogue | | `media.uri` | Accessible HTTPS URL of the source file | | `voice.type` | `runway-preset` | | `voice.presetId` | A preset voice from the request schema, such as `Maya` | Replace the example media URL with your source file. If you use a video, change `media.type` to `video` and supply its video URL in `media.uri`. Set `removeBackgroundNoise: true` to remove background noise from the generated speech. Omit this field to use the model default. ## Retrieve the result Save the returned `id`, then use [Get a Runway task](./runway-to-get-task-details) to retrieve task status. When `status` is `SUCCEEDED`, download the resulting media from the URLs in `output`. If the task fails, inspect `failure` and `failureCode`. # Dub Runway audio Source: https://apidoc.cometapi.com/api/video/runway/official-format/dub-audio api/openapi/video/runway/official-format/post-dub-audio.openapi.json POST /runwayml/v1/voice_dubbing Translate spoken audio into a target language with the Runway API. Use `POST /runwayml/v1/voice_dubbing` to translate spoken audio into another language. Use the model ID `eleven_voice_dubbing`. Send your CometAPI API key with Bearer authentication and a JSON request body. ## Provide audio and a target language Set `audioUri` to an accessible HTTPS URL of your source audio. Set `targetLang` to the destination language code, such as `es` for Spanish or `fr` for French. Select the supported code from the request schema. The request requires `model`, `audioUri`, and `targetLang`. Replace the example audio URL with your source file. ## Configure dubbing | Field | Action | | - | - | | `disableVoiceCloning` | Set `true` to use a generic voice instead of cloning the source voice. | | `dropBackgroundAudio` | Set `true` to remove background audio from the dubbed output. | | `numSpeakers` | Supply a positive integer for the source speaker count, or omit it for automatic detection. | Omit the boolean controls to use the model defaults. Sending `false` also uses the defaults. ## Retrieve the result Save the returned `id`, then use [Get a Runway task](./runway-to-get-task-details) to retrieve task status. When `status` is `SUCCEEDED`, read the audio URLs in `output`. If the task fails, inspect `failure` and `failureCode`. # 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 Edit a video with Runway Aleph 2 through CometAPI, using a text prompt, timed guidance images, and an optional target aspect ratio. Use `aleph2` to edit a source video with a text prompt. The request returns a task `id`; retrieve task details to get the finished output. ## Prepare the request * Authenticate with your CometAPI API key. * Set `model` to `aleph2` and provide `videoUri` for a video of up to 30 seconds. * Optional: include `promptText` to describe the edit, with 1 to 1,000 characters. You can also omit it when using keyframes. * Replace the example media URL with an accessible HTTPS URL. Media fields also accept Base64 data URIs with an encoded size of up to 5 MB. ## Add timed guidance images To guide particular moments, supply one to five objects in `keyframes`. Each object contains an image `uri` and exactly one position: | Field | Meaning | | - | - | | `seconds` | Timestamp from the video start, from `0` through `30` seconds. | | `at` | Fraction of the video duration, from `0` through `1`. | | `range.start_seconds` | Inclusive start of an optional edit window, in whole seconds. | | `range.end_seconds` | Exclusive end of that window, in whole seconds; must exceed its start. | The keyframe timestamp must fall inside its edit window. If you use `range`, set it on every keyframe. Otherwise, omit `range` from every keyframe. Omit `keyframes` when you do not need guidance images. An empty array or `null` is treated as omission. ## Choose the frame shape and format Use `targetAspectRatio` to request expansion to `16:9`, `4:3`, `3:2`, `1:1`, `2:3`, `3:4`, `9:16`, or `21:9`. The input video and guidance images are letterboxed to this shape before generation. The deprecated `ratio` field is optional; use `targetAspectRatio` for aspect-ratio control. | `outputFormat` | Output | | - | - | | `mp4` | H.264 MP4; used when the field is omitted. | | `prores` | ProRes MOV. | | `png_sequence` | ZIP archive containing PNG frames. | | `sdr_rec709_10bit` | 10-bit Rec.709 HEVC MP4. | If `outputFormat` is `prores`, you can set `proresProfile` to `422`, `4444`, `422 Proxy`, `422 LT`, `422 HQ`, or `4444 XQ`. The default profile is `4444`. The alpha channel in `4444` and `4444 XQ` is opaque. Omit `proresProfile` for other output formats. For an explicit sampling seed, use `1` through `4294967295`. Omit `seed` for a random seed; `0` is treated as omission. ## Retrieve the result Save the returned `id` and use [Get a Runway task](./runway-to-get-task-details) to retrieve the task status. When `status` is `SUCCEEDED`, read the result URLs from `output`. If the task fails, inspect `failure` and `failureCode` when present. # Create a Runway text-to-video task Source: https://apidoc.cometapi.com/api/video/runway/official-format/generate-a-video-from-text api/openapi/video/runway/official-format/post-generate-a-video-from-text.openapi.json POST /runwayml/v1/text_to_video Generate a video from a text prompt with Runway Gen-4.5 through CometAPI. Use `gen4.5` to generate a video from a text prompt. Send your CometAPI API key with Bearer authentication and a JSON request body. ## Prepare the request * Set `model` to `gen4.5`. * Describe the scene and motion in `promptText`, using 1 to 1,000 UTF-16 code units. * Set `ratio` to `1280:720` for landscape or `720:1280` for portrait. * Set `duration` to a whole number from `2` through `10` seconds. All four fields are required. To start from an image, use [Create a Runway image-to-video task](./runway-images-raw-video). Do not include `promptImage` or an `audio` toggle in this text-to-video request. ## Set optional controls For an explicit sampling seed, use `1` through `4294967295`. Omission or `0` selects a random seed. If you include `contentModeration`, set its `publicFigureThreshold` to `auto` or `low`; otherwise omit the object. Use `outputFormat` to select MP4, ProRes, PNG sequences, or one of the HDR formats listed in the request schema. Omit it for H.264 MP4. You can set `proresProfile` only when `outputFormat` is `prores` or `hdr_prores`. The HDR ProRes format accepts `422`, `422 HQ`, or `4444`. ## Retrieve the result Save the returned `id` and use [Get a Runway task](./runway-to-get-task-details). When `status` is `SUCCEEDED`, read the video URLs in `output`. # 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 Generate images with Gen-4 Image or Gen-4 Image Turbo using text and reference images. Use this endpoint to generate an image from a prompt, with optional reference images for `gen4_image`. Send your CometAPI API key with Bearer authentication and a JSON request body. ## Choose a model and references Every request requires `model`, `promptText`, and `ratio`. | Model | `referenceImages` | | - | - | | `gen4_image` | Optional. Omit it or use `[]` for text-only generation, or supply up to three images. | | `gen4_image_turbo` | Supply one to three images. | For `gen4_image_turbo`, `referenceImages` is required and must contain one to three images. Each reference object contains an image `uri` and an optional `tag`. Use a tag of 3 to 16 lowercase letters, digits, or underscores, starting with a letter. Reference it in `promptText` as `@tag`, such as `@cat_ref`. Image URIs accept accessible HTTPS URLs or Base64 image data URIs of up to 5 MB. The prompt accepts 1 to 1,000 UTF-16 code units. ## Choose dimensions Set `ratio` to one of the exact dimension pairs in the schema. For example, `1024:1024` requests a square image, `1280:720` a landscape image, and `720:1280` a portrait image. Use `ratio` to select dimensions; do not send `resolution` or `size` with these models. For an explicit sampling seed, use `1` through `4294967295`. Omission or `0` selects a random seed. If you include `contentModeration`, set its `publicFigureThreshold` to `auto` or `low`; otherwise omit the object. ## Retrieve the result Save the returned `id` and use [Get a Runway task](./runway-to-get-task-details). When `status` is `SUCCEEDED`, read the generated image URLs in `output`. # Generate Runway sound effects Source: https://apidoc.cometapi.com/api/video/runway/official-format/generate-sound-effects api/openapi/video/runway/official-format/post-generate-sound-effects.openapi.json POST /runwayml/v1/sound_effect Generate sound effects or audio scenes from a text prompt with the Runway API. Use `POST /runwayml/v1/sound_effect` to create an audio task from a text prompt. Send your CometAPI API key with Bearer authentication and a JSON request body. ## Choose a model | Model ID | Required inputs | Optional controls | | - | - | - | | `eleven_text_to_sound_v2` | `promptText` with 1–3000 characters | `duration` from 0.5 to 30 seconds, including fractional seconds; `loop` | | `seed_audio` | `promptText` with 1–2048 characters | Up to three `referenceAudios`; speech, loudness, and pitch controls; output format | For `eleven_text_to_sound_v2`, omit `duration` to choose the length from the prompt. Set `loop: true` to request a repeating sound effect. For `seed_audio`, refer to `referenceAudios` in the prompt as `@Audio1`, `@Audio2`, and `@Audio3`, in array order. Omit `referenceAudios` when you do not need a reference. Replace each example audio URL with an accessible HTTPS URL of your audio file. Do not include `duration`, `loop`, or `voice` with this model on this endpoint. ## Configure audio controls | Field | Values | Meaning | | - | - | - | | `speechRate` | Integer from -50 to 100 | Negative slows speech; positive speeds it up. | | `loudnessRate` | Integer from -50 to 100 | Negative reduces volume; positive increases it. | | `pitchRate` | Integer from -12 to 12 | Pitch shift in semitones. | | `sampleRate` | `8000`, `16000`, `24000`, `32000`, `44100`, `48000` | Audio sample rate in Hz. | | `outputFormat` | `wav`, `mp3`, `ogg_opus` | Output audio format. | For the three rate controls, omit the field or use `0` to keep its normal value. ## Retrieve the result Save the returned `id`, then use [Get a Runway task](./runway-to-get-task-details) to retrieve task status. When `status` is `SUCCEEDED`, read the audio URLs in `output`. If the task fails, inspect `failure` and `failureCode`. # Generate Runway speech from text Source: https://apidoc.cometapi.com/api/video/runway/official-format/generate-speech-from-text api/openapi/video/runway/official-format/post-generate-speech-from-text.openapi.json POST /runwayml/v1/text_to_speech Convert text into speech with a preset voice or reference audio using the Runway API. Use `POST /runwayml/v1/text_to_speech` to create a speech task from text. Send your CometAPI API key with Bearer authentication and a JSON request body. ## Choose a model and voice Every request requires `model` and `promptText`. The `voice` field is required for `eleven_multilingual_v2`, `eleven_v3`, and `eleven_v4`, and optional for `seed_audio`. | Model ID | Text limit | Voice configuration | | - | - | - | | `eleven_multilingual_v2` | 1000 UTF-16 code units | `type: runway-preset` and a `presetId`, such as `Maya` | | `eleven_v3` | 5000 characters | `type: runway-preset` and a `presetId`, such as `Maya` | | `eleven_v4` | Non-empty text | `type: runway-preset` and a `presetId`, such as `Maya` | | `seed_audio` | 2048 characters | Omit `voice` for a default voice, or use `type: reference-audio` and an `audioUri` | For preset voices, select a `presetId` from the request schema. For `seed_audio`, replace the example `audioUri` with an accessible HTTPS URL of your voice reference. ## Adjust speech expression With `eleven_v3`, `promptText` can include expressive tags such as `[whispers]` or `[laughs]`. The model also accepts these controls: | Field | Values | Meaning | | - | - | - | | `stability` | Number from 0 to 1 | Lower nonzero values allow more expression; higher values are steadier. | | `similarityBoost` | Number from 0 to 1 | Higher values follow the selected voice more closely. | | `style` | Number from 0 to 1 | Higher values emphasize the voice style. | | `speed` | Number from 0.7 to 1.2 | `1` uses normal speed. | | `useSpeakerBoost` | `true` | Request greater similarity to the selected voice. | | `languageCode` | ISO 639-1 language code | Guide pronunciation and text normalization. | | `applyTextNormalization` | `auto`, `on`, `off` | Control how text such as numbers becomes spoken words. | | `seed` | Integer from 1 to 4294967295 | Set the sampling seed. | For `stability`, `similarityBoost`, and `style`, a value of `0` uses the model default, as does omitting the field. `useSpeakerBoost: false` also uses the model default. To set a sampling seed, use a positive integer; `seed: 0` chooses a seed automatically. ## Adjust Eleven v4 speech With `eleven_v4`, `promptText` supports expressive tags such as `[laughs]`, `[whispers]`, and `[pause]`. Use these optional controls: | Field | Values | Meaning | | - | - | - | | `stability` | Number from 0 to 1 | Lower values allow broader emotional range; higher values are steadier. | | `similarityBoost` | Number from 0 to 1 | Set how closely the output tracks the selected voice. | | `style` | Number from 0 to 1 | Higher values amplify the speaker style. | | `speed` | Number from 0.7 to 1.2 | Values below 1 slow speech; values above 1 speed it up. | | `useSpeakerBoost` | `true` or `false` | Boost similarity to the selected voice when `true`. | | `languageCode` | 2–16 characters | Enforce pronunciation, such as `en` or `pt-BR`. | | `previousText` | String | Continue speech from text generated before this request. | | `nextText` | String | Lead speech into text generated after this request. | | `seed` | Integer from 0 to 4294967295 | Choose a seed for more consistent output. | `eleven_v4` does not use `applyTextNormalization`. The `previousText` and `nextText` fields are useful when you generate adjacent segments and want the model to keep the transition coherent. ## Adjust speech speed and format With `seed_audio`, use `speechRate` and `loudnessRate` from -50 to 100, or `pitchRate` from -12 to 12 semitones. These controls accept integers; omission or `0` keeps the normal value. Set `sampleRate` to `8000`, `16000`, `24000`, `32000`, `44100`, or `48000` Hz. Set `outputFormat` to `wav`, `mp3`, or `ogg_opus`. Do not include `duration`, `referenceAudios`, or Eleven v3 controls with `seed_audio` on this endpoint. ## Retrieve the result Save the returned `id`, then use [Get a Runway task](./runway-to-get-task-details) to retrieve task status. When `status` is `SUCCEEDED`, read the audio URLs in `output`. If the task fails, inspect `failure` and `failureCode`. # Isolate a Runway voice Source: https://apidoc.cometapi.com/api/video/runway/official-format/isolate-voice api/openapi/video/runway/official-format/post-isolate-voice.openapi.json POST /runwayml/v1/voice_isolation Separate speech from background audio with the Runway API. Use `POST /runwayml/v1/voice_isolation` to separate speech from background audio. Use the model ID `eleven_voice_isolation`. Send your CometAPI API key with Bearer authentication and a JSON request body. ## Provide source audio The request requires `model` and `audioUri`. Set `audioUri` to an accessible HTTPS URL of the recording that contains the speech to isolate. Replace the example audio URL with your source file. ## Retrieve the result Save the returned `id`, then use [Get a Runway task](./runway-to-get-task-details) to retrieve task status. When `status` is `SUCCEEDED`, read the audio URLs in `output`. If the task fails, inspect `failure` and `failureCode`. # 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 Animate a source image with Gen-4.5 or Gen-4 Turbo and retrieve the result as a Runway task. Use this endpoint to animate a source image. Send your CometAPI API key with Bearer authentication and a JSON request body. ## Choose a model | Model | Required fields | Motion prompt | | - | - | - | | `gen4.5` | `model`, `promptImage`, `promptText`, `ratio`, `duration` | Describe the motion in `promptText`. | | `gen4_turbo` | `model`, `promptImage`, `ratio` | Optionally describe the motion in `promptText`, using 1 to 1,000 UTF-16 code units. | For a text-only request, use [Create a Runway text-to-video task](./generate-a-video-from-text). ## Provide the first frame Set `promptImage` to an accessible HTTPS image URL or a Base64 image data URI. You can also supply a one-item array containing `uri` and `position: "first"`. This interface accepts one starting frame; do not add a last-frame entry. HTTPS images must be directly accessible without redirects and have valid image content headers. Encoded image data URIs can be up to 5 MB. See the [Runway media input requirements](https://docs.dev.runwayml.com/assets/inputs/) for image formats and dimensions. ## Set duration and dimensions Use a whole-number `duration` from `2` through `10` seconds. It is required for `gen4.5` and optional for `gen4_turbo`. Set `ratio` to `1280:720`, `720:1280`, `1104:832`, `960:960`, `832:1104`, or `1584:672`. These are colon-separated width and height values. For an explicit sampling seed, use `1` through `4294967295`. Omission or `0` selects a random seed. If you include `contentModeration`, set its `publicFigureThreshold` to `auto` or `low`; otherwise omit the object. ## Choose an output format `gen4.5` accepts `outputFormat` for MP4, ProRes, PNG sequences, and the HDR formats listed in the request schema. Omit the field for H.264 MP4. `proresProfile` applies only to `prores` and `hdr_prores`; its allowed values depend on the selected format. Omit both fields with `gen4_turbo`. ## Retrieve the result Save the returned `id` and use [Get a Runway task](./runway-to-get-task-details). When `status` is `SUCCEEDED`, read the result URLs in `output`. # 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} Retrieve image, video, or audio task status and output URLs for Runway requests through CometAPI. Use this endpoint with the `id` returned by any `/runwayml/v1` creation request. Authenticate with a CometAPI API key from the same account that created the task. ## Follow the task state The response is a task object. Read `id`, `status`, and `output` directly from the response, without a `data` envelope. | `status` | Next step | | - | - | | Missing, `PENDING`, or `THROTTLED` | Wait a few seconds and request the task again. | | `RUNNING` | Continue polling. `progress`, when present, is a fraction from 0 to 1. | | `SUCCEEDED` | Read result URLs from `output`. | | `FAILED` | Stop polling and inspect `failure` and `failureCode`, when present. | | `CANCELLED` | Stop polling; the task was cancelled. | A freshly submitted task can briefly return HTTP `400` with `code: "task_not_exist"`. Wait a few seconds and retry using the same `id`. If it continues, check the task ID and the account used for authentication. Do not submit the creation request again to check its status. ## Store the output The `output` array contains image, video, or audio URLs according to the creation endpoint and selected format. Download completed assets promptly and store them in your own storage. The result URLs are temporary. For a new integration, choose a model and creation endpoint in the [Runway overview](/api/video/runway/overview). # Upscale a Runway video Source: https://apidoc.cometapi.com/api/video/runway/official-format/upscale-a-video api/openapi/video/runway/official-format/post-upscale-a-video.openapi.json POST /runwayml/v1/video_upscale Upscale a video through CometAPI with Magnific, choosing an output resolution from 720p to 4k and optional detail controls. Use `magnific_video_upscaler_creative` to upscale a source video. The request returns a task `id` for retrieving the finished output. ## Prepare the request * Authenticate with your CometAPI API key. * Set `model` to `magnific_video_upscaler_creative` and provide `videoUri` for a video of up to 30 seconds. * Replace the example video URL with an accessible HTTPS URL. `videoUri` also accepts a Base64 video data URI with an encoded size of up to 5 MB. * Choose `resolution`: `720p`, `1k`, `2k`, or `4k`. Omit the field for `2k`. ## Adjust the enhancement | Field | How to use it | | - | - | | `creativity` | Amount of generated detail to add, from `1` through `100`. | | `sharpen` | Sharpness intensity, from `1` through `100`. | | `smartGrain` | Grain and texture enhancement intensity, from `1` through `100`. | | `flavor` | `vivid` emphasizes color and detail; `natural` favors faithful reproduction. | | `fpsBoost` | Set `true` to request an increased output frame rate. | Omit a numeric control to use the model default. A value of `0` is treated as omission, so it does not explicitly select zero intensity. Likewise, `fpsBoost: false` is treated as omission and does not explicitly disable frame-rate enhancement. Omit optional fields instead of sending `null`. ## Retrieve the result Save the returned `id` and use [Get a Runway task](./runway-to-get-task-details) to retrieve the task status. When `status` is `SUCCEEDED`, read the result URLs from `output`. If the task fails, inspect `failure` and `failureCode` when present. # Runway API overview Source: https://apidoc.cometapi.com/api/video/runway/overview Choose a Runway image, video, or audio model and its CometAPI endpoint, then retrieve the task result. Use Runway models through CometAPI to generate images, create or edit video, produce speech and sound effects, or process audio. Every creation request returns a task `id`; use the task endpoint to retrieve status and output URLs. ## Choose a model and endpoint The following models are available through these Runway endpoints. Each linked reference describes the parameters for its models. | Task | Model IDs | Endpoint | | - | - | - | | Generate an image | `gen4_image`, `gen4_image_turbo` | [Text to image](./official-format/generate-an-image-from-text) | | Animate an image | `gen4.5`, `gen4_turbo` | [Image to video](./official-format/runway-images-raw-video) | | Generate a video from text | `gen4.5` | [Text to video](./official-format/generate-a-video-from-text) | | Edit a video | `aleph2` | [Video to video](./official-format/generate-a-video-from-a-video) | | Animate a character from a performance | `act_two` | [Character performance](./official-format/control-a-character) | | Upscale a video | `magnific_video_upscaler_creative` | [Video upscale](./official-format/upscale-a-video) | | Generate sound effects | `eleven_text_to_sound_v2`, `seed_audio` | [Sound effects](./official-format/generate-sound-effects) | | Generate speech from text | `eleven_multilingual_v2`, `eleven_v3`, `eleven_v4`, `seed_audio` | [Text to speech](./official-format/generate-speech-from-text) | | Convert a voice | `eleven_multilingual_sts_v2` | [Speech to speech](./official-format/convert-speech) | | Dub audio into another language | `eleven_voice_dubbing` | [Voice dubbing](./official-format/dub-audio) | | Separate speech from background audio | `eleven_voice_isolation` | [Voice isolation](./official-format/isolate-voice) | `gen4.5` supports both text-to-video and image-to-video requests. `gen4_turbo` uses image-to-video requests. `seed_audio` has different input fields for sound effects and text-to-speech; follow the selected endpoint's model variant. ## Create a task and retrieve the result **1. Choose the endpoint and model** Select the task above, then use the model-specific request schema and example on that endpoint page. **2. Send the request** [Store your API key locally](/overview/quick-start#store-your-api-key-locally) as `$COMETAPI_KEY` before running the examples. Send JSON to `https://api.cometapi.com/runwayml/v1` followed by the endpoint path. Authenticate with `Authorization: Bearer `. **3. Save the task ID** Save the returned `id` for the task-retrieval request. **4. Retrieve the output** Use [Get a Runway task](./official-format/runway-to-get-task-details) with an API key from the same CometAPI account. When `status` is `SUCCEEDED`, download the assets listed in `output` and store them. For media inputs, use accessible HTTPS URLs or the data URI format shown in the endpoint schema. Replace example media URLs with your own inputs when the example calls for a source video or audio file. # 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 **1. Get your CometAPI API key** 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](https://mintcdn.com/cometapi/SZhlxZhCnMLn__BW/images/overview/810968_364191.png?fit=max\&auto=format\&n=SZhlxZhCnMLn__BW\&q=85\&s=aef81a83f29f8eb16655ed4060425f50) ![CometAPI API key details and base URL](https://mintcdn.com/cometapi/HhtmQffktazbxUvS/images/overview/810968_364193.png?fit=max\&auto=format\&n=HhtmQffktazbxUvS\&q=85\&s=d893f659267150d0faf45f99eb5dffc1) **2. Create a flow and add the CometAPI step** 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](https://mintcdn.com/cometapi/SZhlxZhCnMLn__BW/images/integrations/810968_361326.png?fit=max\&auto=format\&n=SZhlxZhCnMLn__BW\&q=85\&s=20fd998714bb23dc7c28dbad4315c152) ![Search results showing the CometAPI connector](https://mintcdn.com/cometapi/SZhlxZhCnMLn__BW/images/integrations/810968_361327.png?fit=max\&auto=format\&n=SZhlxZhCnMLn__BW\&q=85\&s=084735cca2fbbb0b5e49672c029ff34c) ![Ask CometAPI step selected in the connector list](https://mintcdn.com/cometapi/SZhlxZhCnMLn__BW/images/integrations/810968_361328.png?fit=max\&auto=format\&n=SZhlxZhCnMLn__BW\&q=85\&s=a68000d40dcdfdd14af3a0954ab0c34b) **3. Configure the CometAPI step** 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](https://mintcdn.com/cometapi/SZhlxZhCnMLn__BW/images/integrations/810968_361329.png?fit=max\&auto=format\&n=SZhlxZhCnMLn__BW\&q=85\&s=b3ea4a155f705dfb8cd0956a3cfc7fc8) ![Prompt configuration for the Ask CometAPI step](https://mintcdn.com/cometapi/SZhlxZhCnMLn__BW/images/integrations/810968_361330.png?fit=max\&auto=format\&n=SZhlxZhCnMLn__BW\&q=85\&s=344e62888e22f3ef1d34109e95ee8baf) **4. Test the flow** Click **Test** to run the step. A successful response confirms the integration is working. ![Successful test response from the CometAPI step](https://mintcdn.com/cometapi/SZhlxZhCnMLn__BW/images/integrations/810968_361331.png?fit=max\&auto=format\&n=SZhlxZhCnMLn__BW\&q=85\&s=92fd6c62bcf33f681b053668a9ac6687) > [!NOTE] > > 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 **1. Install Agno** Install Agno in your Python environment: ```bash theme={null} pip install -U agno ``` **2. Set your CometAPI API key** 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 ``` **3. Create an Agno agent** 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). **4. Run the agent** 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 > **Authentication errors** > > 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. > **Model errors** > > 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) **1. Install the provider** 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 ``` **2. Set your API key** 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 ``` > [!NOTE] > > Use environment variables to avoid hardcoding credentials in your source code. **3. Import the provider** 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). > **Tips and troubleshooting** > > * **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 **1. Get your CometAPI API key** 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](https://mintcdn.com/cometapi/SZhlxZhCnMLn__BW/images/overview/810968_364191.png?fit=max\&auto=format\&n=SZhlxZhCnMLn__BW\&q=85\&s=aef81a83f29f8eb16655ed4060425f50) ![CometAPI API key and base URL](https://mintcdn.com/cometapi/HhtmQffktazbxUvS/images/overview/810968_364193.png?fit=max\&auto=format\&n=HhtmQffktazbxUvS\&q=85\&s=d893f659267150d0faf45f99eb5dffc1) **2. Configure the LLM provider** 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. **3. Add your API key and model** 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](https://mintcdn.com/cometapi/E4FFvyMYmaOZoldp/images/integrations/810968_360336.png?fit=max\&auto=format\&n=E4FFvyMYmaOZoldp\&q=85\&s=499826a1508a3749bf0815fe3c7e03df) ![Base URL and API key fields filled in](https://mintcdn.com/cometapi/E4FFvyMYmaOZoldp/images/integrations/810968_360337.png?fit=max\&auto=format\&n=E4FFvyMYmaOZoldp\&q=85\&s=0e882f3675ff64c5c688e95b9629a2d9) ![Model name and token settings configured](https://mintcdn.com/cometapi/E4FFvyMYmaOZoldp/images/integrations/810968_360338.png?fit=max\&auto=format\&n=E4FFvyMYmaOZoldp\&q=85\&s=7c1f49711b3c429b74c9934f69caa7d9) **4. Test the connection** Open a workspace and send a test message. A successful reply confirms the integration is working. ![AnythingLLM chat showing a successful response](https://mintcdn.com/cometapi/E4FFvyMYmaOZoldp/images/integrations/810968_360340.png?fit=max\&auto=format\&n=E4FFvyMYmaOZoldp\&q=85\&s=8d084b71b4df10e71d4ae9c40baf7766) > [!TIP] > > 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 **1. Get your CometAPI API key** 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](https://mintcdn.com/cometapi/SZhlxZhCnMLn__BW/images/overview/810968_364191.png?fit=max\&auto=format\&n=SZhlxZhCnMLn__BW\&q=85\&s=aef81a83f29f8eb16655ed4060425f50) ![CometAPI API key and base URL](https://mintcdn.com/cometapi/HhtmQffktazbxUvS/images/overview/810968_364193.png?fit=max\&auto=format\&n=HhtmQffktazbxUvS\&q=85\&s=d893f659267150d0faf45f99eb5dffc1) **2. Edit your avante.nvim configuration** 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](https://mintcdn.com/cometapi/mA1ovj6s0e3RM42l/images/integrations/810968_351623.png?fit=max\&auto=format\&n=mA1ovj6s0e3RM42l\&q=85\&s=160170230bf813b8887bbb94ffaeafc9) **3. Reload and test** 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) **1. Get your CometAPI API key** 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](https://mintcdn.com/cometapi/SZhlxZhCnMLn__BW/images/overview/810968_364191.png?fit=max\&auto=format\&n=SZhlxZhCnMLn__BW\&q=85\&s=aef81a83f29f8eb16655ed4060425f50) ![CometAPI API key details with base URL](https://mintcdn.com/cometapi/HhtmQffktazbxUvS/images/overview/810968_364193.png?fit=max\&auto=format\&n=HhtmQffktazbxUvS\&q=85\&s=d893f659267150d0faf45f99eb5dffc1) **2. Create a workflow with a REST API trigger** 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. **3. Add the CometAPI Text Generator node** 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](https://mintcdn.com/cometapi/SZhlxZhCnMLn__BW/images/integrations/810968_360694.png?fit=max\&auto=format\&n=SZhlxZhCnMLn__BW\&q=85\&s=4ac17cb84e36a7f026f618e2b5229bf2) ![CometAPI Text Generator node added to the canvas](https://mintcdn.com/cometapi/SZhlxZhCnMLn__BW/images/integrations/810968_360712.png?fit=max\&auto=format\&n=SZhlxZhCnMLn__BW\&q=85\&s=5da7aa2a5bef0d8a9ce45eceace876d1) **4. Link the CometAPI integration** 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](https://mintcdn.com/cometapi/SZhlxZhCnMLn__BW/images/integrations/810968_360713.png?fit=max\&auto=format\&n=SZhlxZhCnMLn__BW\&q=85\&s=ceea3b9fec0cf8a1ab81f70547b0a499) **5. Add your API key to the node** 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](https://mintcdn.com/cometapi/SZhlxZhCnMLn__BW/images/integrations/810968_360715.png?fit=max\&auto=format\&n=SZhlxZhCnMLn__BW\&q=85\&s=25c09a874e2a0ceadf2a83e1192323ca) ![Node showing the key bound successfully](https://mintcdn.com/cometapi/SZhlxZhCnMLn__BW/images/integrations/810968_360714.png?fit=max\&auto=format\&n=SZhlxZhCnMLn__BW\&q=85\&s=7a946cdb3d110605b3a9f1d7d91e022b) **6. Configure input parameters** 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](https://mintcdn.com/cometapi/SZhlxZhCnMLn__BW/images/integrations/810968_360716.png?fit=max\&auto=format\&n=SZhlxZhCnMLn__BW\&q=85\&s=71431b9496c396bbe5fa8d529ca57b27) **7. Add a Return Response node and test** 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](https://mintcdn.com/cometapi/SZhlxZhCnMLn__BW/images/integrations/810968_360717.png?fit=max\&auto=format\&n=SZhlxZhCnMLn__BW\&q=85\&s=561ea8bcdfd96a014dab4476840ee377) 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). > [!TIP] > > 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 **1. Get your CometAPI API key** 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](https://mintcdn.com/cometapi/SZhlxZhCnMLn__BW/images/overview/810968_364191.png?fit=max\&auto=format\&n=SZhlxZhCnMLn__BW\&q=85\&s=aef81a83f29f8eb16655ed4060425f50) ![CometAPI API key and base URL](https://mintcdn.com/cometapi/HhtmQffktazbxUvS/images/overview/810968_364193.png?fit=max\&auto=format\&n=HhtmQffktazbxUvS\&q=85\&s=d893f659267150d0faf45f99eb5dffc1) **2. Configure OpenAI in ChatAll** 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](https://mintcdn.com/cometapi/mA1ovj6s0e3RM42l/images/integrations/810968_351613.png?fit=max\&auto=format\&n=mA1ovj6s0e3RM42l\&q=85\&s=223ae91c7aa6c7a300887a624f6648ba) ![API key field filled in ChatAll settings](https://mintcdn.com/cometapi/mA1ovj6s0e3RM42l/images/integrations/810968_351614.png?fit=max\&auto=format\&n=mA1ovj6s0e3RM42l\&q=85\&s=82546a500cfc0c4f0d161475d08bbf56) **3. Select models** Click the model selector to view and switch between available models. ![ChatAll model selection panel](https://mintcdn.com/cometapi/mA1ovj6s0e3RM42l/images/integrations/810968_351615.png?fit=max\&auto=format\&n=mA1ovj6s0e3RM42l\&q=85\&s=30485dde702fb471d2d2b45cd7f928fe) ![Models listed and selected in ChatAll](https://mintcdn.com/cometapi/mA1ovj6s0e3RM42l/images/integrations/810968_351616.png?fit=max\&auto=format\&n=mA1ovj6s0e3RM42l\&q=85\&s=4dcbfb21b05f291a470c5927cc144999) # 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 **1. Get your CometAPI API key** 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](https://mintcdn.com/cometapi/SZhlxZhCnMLn__BW/images/overview/810968_364191.png?fit=max\&auto=format\&n=SZhlxZhCnMLn__BW\&q=85\&s=aef81a83f29f8eb16655ed4060425f50) ![CometAPI API key and base URL](https://mintcdn.com/cometapi/HhtmQffktazbxUvS/images/overview/810968_364193.png?fit=max\&auto=format\&n=HhtmQffktazbxUvS\&q=85\&s=d893f659267150d0faf45f99eb5dffc1) **2. Configure the API provider** 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](https://mintcdn.com/cometapi/mA1ovj6s0e3RM42l/images/integrations/810968_351530.png?fit=max\&auto=format\&n=mA1ovj6s0e3RM42l\&q=85\&s=897d856de596dae4af3fda696b975dd6) **3. Test the connection** Send a test message in Chatbox. A successful reply confirms the integration is working. ![Chatbox chat window showing a successful response](https://mintcdn.com/cometapi/E4FFvyMYmaOZoldp/images/integrations/810968_360312.png?fit=max\&auto=format\&n=E4FFvyMYmaOZoldp\&q=85\&s=9169ae33248ac9cb492a8a2db68a928b) > [!TIP] > > 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](https://mintcdn.com/cometapi/mA1ovj6s0e3RM42l/images/integrations/810968_351533.png?fit=max\&auto=format\&n=mA1ovj6s0e3RM42l\&q=85\&s=8f40c5a9ebb52b6e664f855c356a8505) # 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 **1. Get your CometAPI API key** 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](https://mintcdn.com/cometapi/SZhlxZhCnMLn__BW/images/overview/810968_364191.png?fit=max\&auto=format\&n=SZhlxZhCnMLn__BW\&q=85\&s=aef81a83f29f8eb16655ed4060425f50) ![CometAPI API key and base URL](https://mintcdn.com/cometapi/HhtmQffktazbxUvS/images/overview/810968_364193.png?fit=max\&auto=format\&n=HhtmQffktazbxUvS\&q=85\&s=d893f659267150d0faf45f99eb5dffc1) **2. Configure OpenAI in ChatHub** 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](https://mintcdn.com/cometapi/mA1ovj6s0e3RM42l/images/integrations/810968_351578.png?fit=max\&auto=format\&n=mA1ovj6s0e3RM42l\&q=85\&s=c4e9ea57615cc53112942cd0eae366c8) ![API key field filled in ChatHub settings](https://mintcdn.com/cometapi/mA1ovj6s0e3RM42l/images/integrations/810968_351579.png?fit=max\&auto=format\&n=mA1ovj6s0e3RM42l\&q=85\&s=dd5c0367a6422ab9eaeea639db6dd55d) **3. Test the connection** Send a test message in ChatHub. A successful reply confirms the integration is working. ![ChatHub showing a successful response from CometAPI](https://mintcdn.com/cometapi/mA1ovj6s0e3RM42l/images/integrations/810968_351580.png?fit=max\&auto=format\&n=mA1ovj6s0e3RM42l\&q=85\&s=46845534e1d30cb2d4897b5d9047b0bf) # 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 **1. Get your CometAPI API key** 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](https://mintcdn.com/cometapi/SZhlxZhCnMLn__BW/images/overview/810968_364191.png?fit=max\&auto=format\&n=SZhlxZhCnMLn__BW\&q=85\&s=aef81a83f29f8eb16655ed4060425f50) ![CometAPI API key and base URL](https://mintcdn.com/cometapi/HhtmQffktazbxUvS/images/overview/810968_364193.png?fit=max\&auto=format\&n=HhtmQffktazbxUvS\&q=85\&s=d893f659267150d0faf45f99eb5dffc1) **2. Add CometAPI as a provider** 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](https://mintcdn.com/cometapi/E4FFvyMYmaOZoldp/images/integrations/810968_355194.png?fit=max\&auto=format\&n=E4FFvyMYmaOZoldp\&q=85\&s=93a035c01494c21065a134748e396381) ![API address and key fields filled in for CometAPI](https://mintcdn.com/cometapi/E4FFvyMYmaOZoldp/images/integrations/810968_355195.png?fit=max\&auto=format\&n=E4FFvyMYmaOZoldp\&q=85\&s=f6edb15b1848812555d0cac24282afcf) **3. Add models** 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](https://mintcdn.com/cometapi/E4FFvyMYmaOZoldp/images/integrations/810968_355196.png?fit=max\&auto=format\&n=E4FFvyMYmaOZoldp\&q=85\&s=9b9f17fe4287de67735320ec5b464e65) **4. Test the connection** Open a chat and send a test message. A successful response confirms the setup is working. ![CherryStudio chat showing a successful response](https://mintcdn.com/cometapi/E4FFvyMYmaOZoldp/images/integrations/810968_360313.png?fit=max\&auto=format\&n=E4FFvyMYmaOZoldp\&q=85\&s=305c5fdce1017d6942aa1176b64f3a96) > [!TIP] > > To add more models, return to the provider settings and click **Add Model** again. > > ![CherryStudio settings showing another custom model added](https://mintcdn.com/cometapi/E4FFvyMYmaOZoldp/images/integrations/810968_355199.png?fit=max\&auto=format\&n=E4FFvyMYmaOZoldp\&q=85\&s=da182754d5fae90778c2c9cc9d5b5727) # 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) > [!NOTE] > > 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 **1. Run the official installer** **macOS / Linux** ```bash theme={null} curl -fsSL https://claude.ai/install.sh | bash ``` **Homebrew** ```bash theme={null} brew install --cask claude-code ``` **Windows** 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 ``` > [!NOTE] > > Windows requires [Git for Windows](https://git-scm.com/downloads/win) installed first. **2. Verify installation** ```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 > **settings.json does not take effect** > > 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" > ``` > **Invalid API Key or Please run /login** > > 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). > **Cached official credentials are used** > > 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 > ``` > **Status shows offline** > > Claude Code checks connectivity via Google. `offline` means Google is unreachable. This does not affect CometAPI usage. > **Fetch or web browsing fails** > > 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) > [!NOTE] > > Claude Desktop third-party inference requires an Anthropic-compatible gateway. CometAPI supports Claude models through the [Anthropic Messages API](/api/text/anthropic-messages). > [!WARNING] > > 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 **1. Enable developer mode** 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`. **2. Open third-party inference settings** 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. **3. Configure the gateway** 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](https://mintcdn.com/cometapi/wsQpBp8rhXV0Hvh3/images/integrations/claude-desktop-cometapi-connection.png?fit=max\&auto=format\&n=wsQpBp8rhXV0Hvh3\&q=85\&s=879de5e2a4587861f220a7f6e0f7d2a5) **4. Add model IDs** 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. > [!TIP] > > 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](https://mintcdn.com/cometapi/wsQpBp8rhXV0Hvh3/images/integrations/claude-desktop-cometapi-model-list.png?fit=max\&auto=format\&n=wsQpBp8rhXV0Hvh3\&q=85\&s=63dcdfe05db59c09782e1514e09a734d) **5. Apply the configuration locally** 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. **6. Start a Cowork session** 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](https://mintcdn.com/cometapi/wsQpBp8rhXV0Hvh3/images/integrations/claude-desktop-cometapi-chat.png?fit=max\&auto=format\&n=wsQpBp8rhXV0Hvh3\&q=85\&s=93bb3b1a60de0d7edbd25cb6ba3b58d8) To inspect the detected settings, open **Help** → **Troubleshooting** → **Copy Managed Configuration Report**. Secret values are redacted in the copied report. ## Troubleshooting > **Developer menu does not appear** > > 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. > **Claude Desktop opens the standard sign-in flow** > > 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. > **Connection validation fails** > > 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. > **Configured models do not appear** > > 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. > **An OpenAI-compatible base URL does not work** > > 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 behaves differently** > > 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 **1. Install Cline in VS Code** Search for **Cline** in the VS Code Extensions panel and install it. ![VS Code Extensions panel showing the Cline extension](https://mintcdn.com/cometapi/mA1ovj6s0e3RM42l/images/integrations/810968_351589.png?fit=max\&auto=format\&n=mA1ovj6s0e3RM42l\&q=85\&s=e7a42db3ea9dfa41a89ff14f23b75dc4) **2. Get your CometAPI API key** 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](https://mintcdn.com/cometapi/SZhlxZhCnMLn__BW/images/overview/810968_364191.png?fit=max\&auto=format\&n=SZhlxZhCnMLn__BW\&q=85\&s=aef81a83f29f8eb16655ed4060425f50) ![CometAPI API key and base URL](https://mintcdn.com/cometapi/HhtmQffktazbxUvS/images/overview/810968_364193.png?fit=max\&auto=format\&n=HhtmQffktazbxUvS\&q=85\&s=d893f659267150d0faf45f99eb5dffc1) **3. Configure the API provider** 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](https://mintcdn.com/cometapi/mA1ovj6s0e3RM42l/images/integrations/810968_351590.png?fit=max\&auto=format\&n=mA1ovj6s0e3RM42l\&q=85\&s=37db10e7d84ac7c4eac050d7021adae4) **4. Test the connection** 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 Connect Codex with CometAPI in two file edits. To connect Codex with CometAPI, [install Codex](https://developers.openai.com/codex/quickstart) and get an API key from the [CometAPI dashboard](https://www.cometapi.com/console/token). ## Quick start: edit two files Edit `config.toml` for the connection and `auth.json` for the API key. Use the `.codex` folder in your user home directory; create the folder or files if missing. **1. Configure config.toml** In `~/.codex/config.toml`, add or update these connection settings: ```toml theme={null} model_provider = "cometapi" model = "your-model-id" [model_providers.cometapi] name = "CometAPI" base_url = "https://api.cometapi.com/v1" requires_openai_auth = true ``` Replace `your-model-id` with a model ID from the [Models page](/overview/models). Keep `model_provider` and `model` above all `[section]` headers. Preserve other settings, and update matching entries instead of adding duplicates. Keep `requires_openai_auth = true` for this method. If switching methods, remove `env_key` and `[model_providers.cometapi.auth]`. **2. Configure auth.json** This method switches Codex to API-key sign-in. If `~/.codex/auth.json` exists, back up the file before replacing its contents: ```json theme={null} { "auth_mode": "apikey", "OPENAI_API_KEY": "" } ``` Replace `` with your CometAPI API key. Keep the field name `OPENAI_API_KEY` unchanged. Save both files, restart Codex, and send a short message to begin. > **Find your Codex configuration directory** > > * **macOS:** In Finder, press **Command + Shift + G** and enter `~/.codex`. > * **Linux:** Open `.codex` in your user home directory. The `~` in `~/.codex` refers to your home directory. > * **Windows native:** In File Explorer, enter `%USERPROFILE%\.codex`, usually `C:\Users\\.codex`. > * **WSL:** Use `~/.codex` inside the Linux distribution where Codex runs. > > If you set `CODEX_HOME`, use that directory for both files. Configure the user-level files rather than a project's `.codex/config.toml`. ## Compare configuration methods | Method | API key location | ChatGPT sign-in | | - | - | - | | [Two-file quick start](#quick-start-edit-two-files) | `~/.codex/auth.json` | Switches to API-key sign-in | | [Recommended configuration](#recommended-configuration) | `~/.codex/cometapi_key` | Leaves stored ChatGPT sign-in unchanged | To keep your ChatGPT sign-in, use the recommended configuration below. ## Recommended configuration This is the recommended configuration. It stores your CometAPI API key in a separate file and reads the API key with a command. It leaves `~/.codex/auth.json` unchanged. > [!NOTE] > > For this method, remove `requires_openai_auth` and `env_key` from `[model_providers.cometapi]`. Do not combine these fields with `[model_providers.cometapi.auth]`. > > If you previously used the quick start and want to restore ChatGPT sign-in, restore your `auth.json` backup or sign in with ChatGPT again. **macOS / Linux / WSL** Replace `` with your CometAPI API key and store the API key in a local file: ```bash theme={null} mkdir -p "$HOME/.codex" printf "%s\n" "" > "$HOME/.codex/cometapi_key" chmod 600 "$HOME/.codex/cometapi_key" ``` Add or update this configuration in `~/.codex/config.toml`. Replace `your-model-id` with the model ID: ```toml theme={null} model_provider = "cometapi" model = "your-model-id" [model_providers.cometapi] name = "CometAPI" base_url = "https://api.cometapi.com/v1" [model_providers.cometapi.auth] command = "sh" args = ["-c", "cat \"$HOME/.codex/cometapi_key\""] ``` **Windows PowerShell** Replace `` with your CometAPI API key and store the 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 "" ``` Add or update this configuration in `$HOME\.codex\config.toml`. Replace `your-model-id` with the model ID: ```toml theme={null} model_provider = "cometapi" model = "your-model-id" [model_providers.cometapi] name = "CometAPI" base_url = "https://api.cometapi.com/v1" [model_providers.cometapi.auth] command = "powershell.exe" args = [ "-NoProfile", "-Command", "$p=Join-Path $HOME '.codex/cometapi_key'; (Get-Content -Raw $p).Trim()", ] ``` ## 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. Set `COMETAPI_KEY` to your CometAPI API key in the environment that launches Codex. Use this configuration and replace `your-model-id` with the model ID: ```toml theme={null} model_provider = "cometapi" model = "your-model-id" [model_providers.cometapi] name = "CometAPI" base_url = "https://api.cometapi.com/v1" env_key = "COMETAPI_KEY" ``` > [!WARNING] > > Remove `requires_openai_auth` and `[model_providers.cometapi.auth]` when using `env_key`. ## Run the setup script The optional setup script applies the recommended command authentication. It updates `~/.codex/config.toml`, stores your CometAPI API key in `~/.codex/cometapi_key`, and creates backups before file changes. It also 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, replace `` and pass the API key explicitly: ```bash theme={null} curl -fsSL https://raw.githubusercontent.com/cometapi-dev/integrations/main/codex/setup.sh | sh -s -- --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, replace `` and 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 ''" ``` > [!WARNING] > > By default, the script leaves `~/.codex/auth.json` unchanged. Use `--force-auth-json` or `-ForceAuthJson` to select the quick start's API-key sign-in method. This option writes `auth.json` and sets `requires_openai_auth = true` instead of command authentication. ## 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, replace `` and `your-model-id` when running the setup script: ```bash theme={null} curl -fsSL https://raw.githubusercontent.com/cometapi-dev/integrations/main/codex/setup.sh | sh -s -- --key "" --model your-model-id ``` For Windows native PowerShell, replace `` and `your-model-id` when running the setup script: ```powershell theme={null} powershell -c "& ([scriptblock]::Create((irm 'https://raw.githubusercontent.com/cometapi-dev/integrations/main/codex/setup.ps1'))) -Key '' -Model 'your-model-id'" ``` > [!NOTE] > > The script uses `CODEX_HOME` when it is set. Otherwise it writes to the current environment's `~/.codex`. ## Verify the setup Save your configuration and restart Codex before checking the connection. 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 > **Codex still uses the default OpenAI provider** > > Confirm that `model_provider = "cometapi"` is in the user-level `~/.codex/config.toml` file. > **The API key changed** > > For the quick start, update `OPENAI_API_KEY` in `~/.codex/auth.json`. For the recommended configuration, update `~/.codex/cometapi_key`. For environment authentication, update `COMETAPI_KEY` in the environment that launches Codex. Restart Codex after changing the API key. > **Authentication settings conflict** > > Choose one authentication method. The quick start uses `requires_openai_auth = true` and `auth.json`. Command authentication uses `[model_providers.cometapi.auth]` without `requires_openai_auth` or `env_key`. Environment authentication uses `env_key` without the other two settings. > **The PowerShell script fails during pre-flight checks** > > Use the manual Windows native PowerShell steps, then run the verification command. > **The piped shell setup asks for no API key** > > Pass `--key ""` with your CometAPI API key, or run the interactive installer from [Run the setup script](#run-the-setup-script). > **The connection times out or uses the wrong base URL** > > Confirm that `base_url` is `https://api.cometapi.com/v1` in `~/.codex/config.toml`. > **The model is not found** > > Check the [Models page](/overview/models) for available model IDs. > **Windows setup affects the wrong environment** > > Edit `$HOME\.codex` for Windows native mode, or edit `~/.codex` inside WSL for WSL agent mode. > **The ChatGPT login changed** > > The quick start and the script's `--force-auth-json` or `-ForceAuthJson` option select API-key sign-in. To use ChatGPT sign-in again, restore your `auth.json` backup or sign in with ChatGPT, then use the [recommended configuration](#recommended-configuration). ## 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) # 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 **1. Install Continue in VS Code** Search for **Continue** in the VS Code Extensions panel and install it. ![VS Code Extensions panel showing the Continue extension](https://mintcdn.com/cometapi/SZhlxZhCnMLn__BW/images/integrations/810968_362621.png?fit=max\&auto=format\&n=SZhlxZhCnMLn__BW\&q=85\&s=6e94ab329f18d8e02387dc6fe8c798e3) **2. Get your CometAPI API key** Log in to the [CometAPI dashboard](https://www.cometapi.com/console). Click **Add API Key** and copy your key. ![CometAPI dashboard — Add API Key](https://mintcdn.com/cometapi/SZhlxZhCnMLn__BW/images/overview/810968_364191.png?fit=max\&auto=format\&n=SZhlxZhCnMLn__BW\&q=85\&s=aef81a83f29f8eb16655ed4060425f50) ![CometAPI API key and base URL](https://mintcdn.com/cometapi/HhtmQffktazbxUvS/images/overview/810968_364193.png?fit=max\&auto=format\&n=HhtmQffktazbxUvS\&q=85\&s=d893f659267150d0faf45f99eb5dffc1) **3. Add CometAPI as a provider** 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](https://mintcdn.com/cometapi/SZhlxZhCnMLn__BW/images/integrations/810968_362622.png?fit=max\&auto=format\&n=SZhlxZhCnMLn__BW\&q=85\&s=7d9ad8d97240036f8eabad68ac872f7e) ![CometAPI provider configuration in Continue](https://mintcdn.com/cometapi/SZhlxZhCnMLn__BW/images/integrations/810968_362623.png?fit=max\&auto=format\&n=SZhlxZhCnMLn__BW\&q=85\&s=53d3b5b690328196cbc0c7aeeb39ad9b) ![Model selection in Continue with CometAPI provider](https://mintcdn.com/cometapi/SZhlxZhCnMLn__BW/images/integrations/810968_362624.png?fit=max\&auto=format\&n=SZhlxZhCnMLn__BW\&q=85\&s=e9fee9dd542d42a4415f0a41827124e5) **4. Test the connection** 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](https://mintcdn.com/cometapi/SZhlxZhCnMLn__BW/images/integrations/810968_362626.png?fit=max\&auto=format\&n=SZhlxZhCnMLn__BW\&q=85\&s=765ce3c34f80b122bab7b763d970bd4f) > [!NOTE] > > 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](https://mintcdn.com/cometapi/SZhlxZhCnMLn__BW/images/integrations/810968_362627.png?fit=max\&auto=format\&n=SZhlxZhCnMLn__BW\&q=85\&s=54d4157b18c9134ec966daf66ec36e45) # 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) **1. Get your CometAPI API key** 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](https://mintcdn.com/cometapi/SZhlxZhCnMLn__BW/images/overview/810968_364191.png?fit=max\&auto=format\&n=SZhlxZhCnMLn__BW\&q=85\&s=aef81a83f29f8eb16655ed4060425f50) ![CometAPI API key details with base URL](https://mintcdn.com/cometapi/HhtmQffktazbxUvS/images/overview/810968_364193.png?fit=max\&auto=format\&n=HhtmQffktazbxUvS\&q=85\&s=d893f659267150d0faf45f99eb5dffc1) **2. Add CometAPI to a Coze workflow** **Method 1: CometAPI Plugin (Recommended)** 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](https://mintcdn.com/cometapi/E4FFvyMYmaOZoldp/images/integrations/810968_355124.png?fit=max\&auto=format\&n=E4FFvyMYmaOZoldp\&q=85\&s=31a8c613d735f88246baa86ae399fa11) ![CometAPI plugin appearing in search results](https://mintcdn.com/cometapi/E4FFvyMYmaOZoldp/images/integrations/810968_355125.png?fit=max\&auto=format\&n=E4FFvyMYmaOZoldp\&q=85\&s=75f2336cc40c9f21d757ced6ee227fd7) ![CometAPI plugin node added to canvas](https://mintcdn.com/cometapi/E4FFvyMYmaOZoldp/images/integrations/810968_355126.png?fit=max\&auto=format\&n=E4FFvyMYmaOZoldp\&q=85\&s=1058980811bfc31c51715a76e048cc02) ![Plugin node configuration panel](https://mintcdn.com/cometapi/E4FFvyMYmaOZoldp/images/integrations/810968_360283.png?fit=max\&auto=format\&n=E4FFvyMYmaOZoldp\&q=85\&s=f89b117699a4d46802c62436ae92bd84) 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](https://mintcdn.com/cometapi/SZhlxZhCnMLn__BW/images/integrations/810968_361332.png?fit=max\&auto=format\&n=SZhlxZhCnMLn__BW\&q=85\&s=0f41c0cfaf3cdcebd45d740ce96fd178) ![Successful test result for the CometAPI plugin](https://mintcdn.com/cometapi/SZhlxZhCnMLn__BW/images/integrations/810968_361333.png?fit=max\&auto=format\&n=SZhlxZhCnMLn__BW\&q=85\&s=17b349b2c651c6e5193bfde6b63e0c17) **Method 2: HTTP Request Node** 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](https://mintcdn.com/cometapi/E4FFvyMYmaOZoldp/images/integrations/810968_355128.png?fit=max\&auto=format\&n=E4FFvyMYmaOZoldp\&q=85\&s=862c588b2f301bd66b89366c5344fbdc) ![Request body JSON configured in the HTTP node](https://mintcdn.com/cometapi/E4FFvyMYmaOZoldp/images/integrations/810968_355129.png?fit=max\&auto=format\&n=E4FFvyMYmaOZoldp\&q=85\&s=a438417210684dddf988307c448edb57) ![End node with HTTP response body selected as output](https://mintcdn.com/cometapi/E4FFvyMYmaOZoldp/images/integrations/810968_355130.png?fit=max\&auto=format\&n=E4FFvyMYmaOZoldp\&q=85\&s=18254fe80669e295bd7b8ac2e48c3d45) ![Coze workflow with all nodes connected](https://mintcdn.com/cometapi/E4FFvyMYmaOZoldp/images/integrations/810968_355131.png?fit=max\&auto=format\&n=E4FFvyMYmaOZoldp\&q=85\&s=5fde76e14e42d41311076f7eb1d0fd77) **3. Test and publish** 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](https://mintcdn.com/cometapi/E4FFvyMYmaOZoldp/images/integrations/810968_360285.png?fit=max\&auto=format\&n=E4FFvyMYmaOZoldp\&q=85\&s=5f362ef3274c53c47a8f3793d4fa6966) ![Published Coze agent responding correctly](https://mintcdn.com/cometapi/E4FFvyMYmaOZoldp/images/integrations/810968_355132.png?fit=max\&auto=format\&n=E4FFvyMYmaOZoldp\&q=85\&s=8b7fe683331ec5cb31222062c6f3aa80) If the call fails, verify your API key and endpoint URL, or contact [CometAPI support](https://www.cometapi.com). > [!TIP] > > 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 **1. Create a project and install CrewAI** 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]' ``` **2. Set your API key and model IDs** 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. **3. Create the sequential Crew** 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. **4. Run the Crew** 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 > **Anthropic or Gemini provider imports fail** > > Run `uv add 'crewai[anthropic,google-genai]'` in the project. The base CrewAI package does not install both optional provider SDKs by default. > **A Responses request returns a parameter error** > > Remove optional parameters that are not part of the selected model's interface. The example configures only the output token limit for Responses. > **A request uses the wrong route** > > 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) # Use DeepSeek Harness with CometAPI Source: https://apidoc.cometapi.com/integrations/deepseek-harness Configure DeepSeek Harness 0.1.0-rc.8 to use CometAPI through Chat Completions, Responses, Anthropic Messages, or Google generateContent. Use this guide to run [DeepSeek Harness](https://github.com/deepseek-ai/deepseek-harness) with CometAPI. DeepSeek Harness loads custom model providers from `$DSH_HOME/settings.yaml`, which defaults to `~/.dsh/settings.yaml`. The configurations on this page were verified with `@deepseek-ai/dsh@0.1.0-rc.8`. Each route completed a streaming text turn and a file-reading tool loop with one representative model. This scope does not mean that every CometAPI model accepts every API format. > [!WARNING] > > DeepSeek Harness is in Developer Preview and can introduce breaking changes. Pin the tested package version when following this guide, and review the upstream release notes before upgrading. Official references: * [DeepSeek Harness repository](https://github.com/deepseek-ai/deepseek-harness) * [DeepSeek Harness 0.1.0-rc.8 source](https://github.com/deepseek-ai/deepseek-harness/tree/dsh-v0.1.0-rc.8) * [DeepSeek Harness CLI](https://github.com/deepseek-ai/deepseek-harness/blob/dsh-v0.1.0-rc.8/apps/cli/README.md) * [DeepSeek Harness provider guide](https://github.com/deepseek-ai/deepseek-harness/blob/dsh-v0.1.0-rc.8/docs/user/guide/providers.md) ## Prerequisites * Node.js and npm * A CometAPI account with an active API key from the [dashboard](https://www.cometapi.com/console/token) * A model ID from the [CometAPI Models page](/overview/models) for each API format you plan to use ## Understand the provider routes The `api` value selects the wire format. The `baseURL` stops before the operation path that Harness appends. | Provider ID | `api` value | `baseURL` | Request path | | - | - | - | - | | `cometapi-chat` | `openai-completions` | `https://api.cometapi.com/v1` | `/v1/chat/completions` | | `cometapi-responses` | `openai-responses` | `https://api.cometapi.com/v1` | `/v1/responses` | | `cometapi-messages` | `anthropic-messages` | `https://api.cometapi.com` | `/v1/messages` | > [!NOTE] > > Replace each `your-model-id` value independently. Choose a model that accepts the API format of its provider entry. ## Configure the providers **1. Confirm the tested Harness version** Confirm the pinned package version before configuring Harness: ```bash theme={null} npx @deepseek-ai/dsh@0.1.0-rc.8 --version ``` The command should print `0.1.0-rc.8`. **2. Set your CometAPI API key** Store your key in `COMETAPI_KEY` before starting Harness: ```bash theme={null} read -rsp "CometAPI API key: " COMETAPI_KEY printf '\n' export COMETAPI_KEY ``` Set the variable in every shell session that launches Harness. Do not commit API keys to version control. **3. Add the CometAPI providers** Create `$DSH_HOME/settings.yaml`. If the file already has an `llm-pi-ai` section, merge these provider entries into its existing `providers` map: ```yaml theme={null} llm-pi-ai: providers: cometapi-chat: displayName: CometAPI Chat Completions apiKeyEnv: COMETAPI_KEY api: openai-completions baseURL: https://api.cometapi.com/v1 models: - id: your-model-id cometapi-responses: displayName: CometAPI Responses apiKeyEnv: COMETAPI_KEY api: openai-responses baseURL: https://api.cometapi.com/v1 models: - id: your-model-id cometapi-messages: displayName: CometAPI Anthropic Messages apiKeyEnv: COMETAPI_KEY api: anthropic-messages baseURL: https://api.cometapi.com models: - id: your-model-id agent-default-model: provider: cometapi-responses model: your-model-id ``` The example selects the Responses provider by default. Change `agent-default-model.provider` and `agent-default-model.model` to select another configured entry. If you prefer the Web UI, start it after exporting `COMETAPI_KEY`, then use its model settings to add or edit provider entries and select the default model: ```bash theme={null} npx @deepseek-ai/dsh@0.1.0-rc.8 web ``` The default local address is `http://127.0.0.1:3080`. YAML remains the direct path for matching the route names and base URLs in this guide. **4. Verify a text turn** Run a one-shot headless task from the project directory you want Harness to use: ```bash theme={null} npx @deepseek-ai/dsh@0.1.0-rc.8 \ --profile headless \ "Reply exactly with: COMETAPI_DSH_OK" ``` A successful run prints `COMETAPI_DSH_OK`. To check another provider, update `agent-default-model` and run the command again. **5. Verify file tool use** Create a temporary sentinel file, then ask Harness to read it with a file tool: ```bash theme={null} printf 'COMETAPI_DSH_TOOL_OK\n' > /tmp/cometapi-dsh-sentinel.txt npx @deepseek-ai/dsh@0.1.0-rc.8 \ --profile headless \ "Read /tmp/cometapi-dsh-sentinel.txt with a file tool, then reply with only its contents." ``` Confirm that the final answer is `COMETAPI_DSH_TOOL_OK`. Run Harness only in a workspace where you accept its file, process, and network access. ## Optional route Harness has one built-in provider route named `google`. The configuration below points that route at CometAPI, so it replaces the route's native Google endpoint instead of adding a second Google route. Merge this entry into `llm-pi-ai.providers`, then select it in `agent-default-model`: ```yaml theme={null} llm-pi-ai: providers: google: displayName: CometAPI Google generateContent apiKeyEnv: COMETAPI_KEY baseURL: https://api.cometapi.com/v1beta models: - id: your-model-id agent-default-model: provider: google model: your-model-id ``` Do not add an `api` field to this entry. The built-in `google` route keeps its native Google protocol and sends streaming requests to `/v1beta/models/{model}:streamGenerateContent?alt=sse` with `x-goog-api-key` authentication. ## Troubleshooting > **Harness reports that the API key is missing** > > Confirm that `COMETAPI_KEY` is set in the same shell that launches Harness. Restart Harness after changing the environment variable. > **Harness does not show the configured model** > > Confirm that `$DSH_HOME/settings.yaml` is valid YAML, the provider is under `llm-pi-ai.providers`, and the model is listed under that provider's `models`. The default `DSH_HOME` is `~/.dsh`. > **Chat Completions or Responses uses the wrong path** > > Use `https://api.cometapi.com/v1` as `baseURL`. Do not append `/chat/completions` or `/responses`; Harness appends the operation path. > **Anthropic Messages returns a path error** > > Use `https://api.cometapi.com` without `/v1` as the Messages `baseURL`. The Anthropic adapter appends `/v1/messages`. > **Google generates a duplicated v1beta path** > > Use `https://api.cometapi.com/v1beta` exactly. Do not append a model path, and do not add an `api` field to the built-in `google` route. > **A model works on one provider but not another** > > Model availability and accepted API formats can differ. Choose a model for each provider entry instead of assuming one model works across all four formats. > **Configuration stops working after an upgrade** > > DeepSeek Harness is in Developer Preview. Return to `@deepseek-ai/dsh@0.1.0-rc.8`, then review upstream changes before adapting the configuration to another version. ## Related resources * [CometAPI quick start](/overview/quick-start) * [CometAPI Models page](/overview/models) * [DeepSeek Harness repository](https://github.com/deepseek-ai/deepseek-harness) * [DeepSeek Harness provider guide](https://github.com/deepseek-ai/deepseek-harness/blob/dsh-v0.1.0-rc.8/docs/user/guide/providers.md) # 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. **1. Get your CometAPI API key** 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](https://mintcdn.com/cometapi/SZhlxZhCnMLn__BW/images/overview/810968_364191.png?fit=max\&auto=format\&n=SZhlxZhCnMLn__BW\&q=85\&s=aef81a83f29f8eb16655ed4060425f50) ![CometAPI API key details showing the base URL https://api.cometapi.com](https://mintcdn.com/cometapi/HhtmQffktazbxUvS/images/overview/810968_364193.png?fit=max\&auto=format\&n=HhtmQffktazbxUvS\&q=85\&s=d893f659267150d0faf45f99eb5dffc1) **2. Install the CometAPI plugin in Dify** In Dify, go to **Plugins** → **Install Plugin** → **Marketplace**. Search for `cometapi` and install it. ![Dify plugin marketplace search results showing the CometAPI plugin](https://mintcdn.com/cometapi/E4FFvyMYmaOZoldp/images/integrations/810968_360267.png?fit=max\&auto=format\&n=E4FFvyMYmaOZoldp\&q=85\&s=85e4b1a60c912aa98c182ed731cde19f) ![CometAPI plugin installation confirmation dialog in Dify](https://mintcdn.com/cometapi/E4FFvyMYmaOZoldp/images/integrations/810968_360269.png?fit=max\&auto=format\&n=E4FFvyMYmaOZoldp\&q=85\&s=695d0f5fde8d4c8aad398048b3b504fd) **3. Add your API key** Go to **Settings** → **Model Provider** → **CometAPI** → **Open Settings**. Paste your CometAPI API key and click **Save**. **4. Add models** Enter a model ID from the [CometAPI Models page](/overview/models) and click **Add**. ![Dify model provider settings showing the CometAPI configuration form](https://mintcdn.com/cometapi/SZhlxZhCnMLn__BW/images/integrations/810968_362636.png?fit=max\&auto=format\&n=SZhlxZhCnMLn__BW\&q=85\&s=9aee58e6532ba58d69eb7673e6c45293) ![Dify model list with CometAPI models successfully added](https://mintcdn.com/cometapi/SZhlxZhCnMLn__BW/images/integrations/810968_362637.png?fit=max\&auto=format\&n=SZhlxZhCnMLn__BW\&q=85\&s=46c8b360d87cfad2adc1cd9f18dd7f25) **5. Test the connection** 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](https://mintcdn.com/cometapi/SZhlxZhCnMLn__BW/images/integrations/810968_362638.png?fit=max\&auto=format\&n=SZhlxZhCnMLn__BW\&q=85\&s=c729bbc0f3bef82a89305434c08ec313) ## 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. **1. Open model provider settings** Go to **Settings** → **Model Provider** → **OpenAI-API-compatible** → **Add Model**. **2. Configure the 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](https://mintcdn.com/cometapi/E4FFvyMYmaOZoldp/images/integrations/810968_354447.png?fit=max\&auto=format\&n=E4FFvyMYmaOZoldp\&q=85\&s=a6752a58cf43a3c7658da7b276ed5c1e) ![Dify model list showing a newly saved CometAPI-compatible model entry](https://mintcdn.com/cometapi/E4FFvyMYmaOZoldp/images/integrations/810968_354448.png?fit=max\&auto=format\&n=E4FFvyMYmaOZoldp\&q=85\&s=18caf18d11f4f0aa6741471016bcb14f) > [!TIP] > > 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 > **The API key fails** > > Confirm that the API key is correct and has available balance. > **The model ID fails** > > Confirm that the model ID matches exactly what CometAPI expects. > **The API base URL fails** > > Confirm that the API base URL includes `/v1` for the OpenAI-compatible method. > **Further help** > > 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](https://mintcdn.com/cometapi/mA1ovj6s0e3RM42l/images/integrations/810968_351582.png?fit=max\&auto=format\&n=mA1ovj6s0e3RM42l\&q=85\&s=b9bc1e823b935085dd27b3c84620b012) * A [CometAPI](https://www.cometapi.com) account with an active API key ## Setup **1. Get your CometAPI API key** 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](https://mintcdn.com/cometapi/SZhlxZhCnMLn__BW/images/overview/810968_364191.png?fit=max\&auto=format\&n=SZhlxZhCnMLn__BW\&q=85\&s=aef81a83f29f8eb16655ed4060425f50) ![CometAPI API key and base URL](https://mintcdn.com/cometapi/HhtmQffktazbxUvS/images/overview/810968_364193.png?fit=max\&auto=format\&n=HhtmQffktazbxUvS\&q=85\&s=d893f659267150d0faf45f99eb5dffc1) **2. Add a custom translation engine** 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. **3. Configure your API key and model** Paste your CometAPI key into the **API Key** field. Optionally enter a specific model ID. Click **Save**. ![Eudic add translation engine dialog](https://mintcdn.com/cometapi/mA1ovj6s0e3RM42l/images/integrations/810968_351583.png?fit=max\&auto=format\&n=mA1ovj6s0e3RM42l\&q=85\&s=95b61b747f61ebfbccbe9fbdd08efa9c) ![API host and key fields filled in for CometAPI](https://mintcdn.com/cometapi/mA1ovj6s0e3RM42l/images/integrations/810968_351584.png?fit=max\&auto=format\&n=mA1ovj6s0e3RM42l\&q=85\&s=b9035ae781d010889e40d1f1e1f663c5) ![Model name field in Eudic translation engine settings](https://mintcdn.com/cometapi/mA1ovj6s0e3RM42l/images/integrations/810968_351585.png?fit=max\&auto=format\&n=mA1ovj6s0e3RM42l\&q=85\&s=25957b51623bff5f02aab265a13eb943) **4. Test the translation** 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 **1. Get your CometAPI API key** 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](https://mintcdn.com/cometapi/SZhlxZhCnMLn__BW/images/overview/810968_364191.png?fit=max\&auto=format\&n=SZhlxZhCnMLn__BW\&q=85\&s=aef81a83f29f8eb16655ed4060425f50) ![CometAPI API key and base URL](https://mintcdn.com/cometapi/HhtmQffktazbxUvS/images/overview/810968_364193.png?fit=max\&auto=format\&n=HhtmQffktazbxUvS\&q=85\&s=d893f659267150d0faf45f99eb5dffc1) **2. Add CometAPI as a third-party account** 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](https://mintcdn.com/cometapi/E4FFvyMYmaOZoldp/images/integrations/810968_355099.png?fit=max\&auto=format\&n=E4FFvyMYmaOZoldp\&q=85\&s=e1ef9869db75622178961784ac09ad57) ![URL and API key fields filled in for CometAPI in FastGPT](https://mintcdn.com/cometapi/E4FFvyMYmaOZoldp/images/integrations/810968_355100.png?fit=max\&auto=format\&n=E4FFvyMYmaOZoldp\&q=85\&s=0e7fcb0a8cc9fb390aa9911795252967) **3. Test the connection** 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](https://mintcdn.com/cometapi/E4FFvyMYmaOZoldp/images/integrations/810968_355101.png?fit=max\&auto=format\&n=E4FFvyMYmaOZoldp\&q=85\&s=e8c96cab8e14e0be6ddd6c0f48c43b8f) > [!WARNING] > > 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. > [!NOTE] > > 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 **1. Get your CometAPI API key** 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](https://mintcdn.com/cometapi/SZhlxZhCnMLn__BW/images/overview/810968_364191.png?fit=max\&auto=format\&n=SZhlxZhCnMLn__BW\&q=85\&s=aef81a83f29f8eb16655ed4060425f50) ![CometAPI API key details with base URL](https://mintcdn.com/cometapi/HhtmQffktazbxUvS/images/overview/810968_364193.png?fit=max\&auto=format\&n=HhtmQffktazbxUvS\&q=85\&s=d893f659267150d0faf45f99eb5dffc1) **2. Add the ChatCometAPI node** 1. In your FlowiseAI chatflow canvas, click **Add New**. ![FlowiseAI canvas with the Add New button](https://mintcdn.com/cometapi/SZhlxZhCnMLn__BW/images/integrations/810968_361945.png?fit=max\&auto=format\&n=SZhlxZhCnMLn__BW\&q=85\&s=f36fc7cc6d541af1acd95f6b8aea9b04) 2. Search for **cometapi** and select the **ChatCometAPI** node. ![Node search showing ChatCometAPI result](https://mintcdn.com/cometapi/SZhlxZhCnMLn__BW/images/integrations/810968_361946.png?fit=max\&auto=format\&n=SZhlxZhCnMLn__BW\&q=85\&s=0da9222351e5378eeeb928b1acf1e959) 3. Drag it onto the canvas. ![ChatCometAPI node placed on the canvas](https://mintcdn.com/cometapi/SZhlxZhCnMLn__BW/images/integrations/810968_361947.png?fit=max\&auto=format\&n=SZhlxZhCnMLn__BW\&q=85\&s=c727ab9ff734355a0f2d5de4ff479c97) **3. Create the CometAPI credential** 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](https://mintcdn.com/cometapi/SZhlxZhCnMLn__BW/images/integrations/810968_361948.png?fit=max\&auto=format\&n=SZhlxZhCnMLn__BW\&q=85\&s=b64309fa10d20704751e433c3316cf82) **4. Set the CometAPI base path** 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 **1. Add a Prompt Template** 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](https://mintcdn.com/cometapi/SZhlxZhCnMLn__BW/images/integrations/810968_361949.png?fit=max\&auto=format\&n=SZhlxZhCnMLn__BW\&q=85\&s=201c0e040b56a7a5338ba34b5761cac1) ![Prompt Template node placed on canvas](https://mintcdn.com/cometapi/SZhlxZhCnMLn__BW/images/integrations/810968_361950.png?fit=max\&auto=format\&n=SZhlxZhCnMLn__BW\&q=85\&s=9a872c659549ba024457a015a5c75064) **2. Add an LLM Chain** 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](https://mintcdn.com/cometapi/SZhlxZhCnMLn__BW/images/integrations/810968_361951.png?fit=max\&auto=format\&n=SZhlxZhCnMLn__BW\&q=85\&s=a44d838bb2fc70911e0407b1ea2ed7f2) **3. Save and test the flow** 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](https://mintcdn.com/cometapi/SZhlxZhCnMLn__BW/images/integrations/810968_361954.png?fit=max\&auto=format\&n=SZhlxZhCnMLn__BW\&q=85\&s=73647ee6f0995ed8c36a9fd1a2e6fd97) ## 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. **1. Create and process a Document 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. **2. Configure embeddings and vector storage** 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. **3. Create the retrieval 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. **4. Connect Conversational Retrieval QA Chain** 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 > **The ChatCometAPI node is missing** > > 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. > **Requests fail because the base path is wrong** > > 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`. > **The API key or credential fails** > > 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. > **The model ID fails** > > 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. > **The workflow tries to generate images** > > 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. > **RAG returns no sources or weak answers** > > 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**. > **Upsert or vector store configuration fails** > > 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. > **The request times out or is rate limited** > > 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) > [!NOTE] > > 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 **1. Install Gemini CLI** ```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 ``` **2. Set environment variables** ```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. **3. Start Gemini CLI** ```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 > **Invalid API Key error** > > Verify `GEMINI_API_KEY` is set correctly. Run `echo $GEMINI_API_KEY` to check. > **fetch failed** > > Network restrictions may block the connection. Try a system-wide proxy. > **Wrong Node.js version** > > Gemini CLI requires Node.js 22+. Run `node --version` to check. > **Uninstall Gemini CLI** > > 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 **1. Get your CometAPI API key** 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](https://mintcdn.com/cometapi/SZhlxZhCnMLn__BW/images/overview/810968_364191.png?fit=max\&auto=format\&n=SZhlxZhCnMLn__BW\&q=85\&s=aef81a83f29f8eb16655ed4060425f50) ![CometAPI API key and base URL](https://mintcdn.com/cometapi/HhtmQffktazbxUvS/images/overview/810968_364193.png?fit=max\&auto=format\&n=HhtmQffktazbxUvS\&q=85\&s=d893f659267150d0faf45f99eb5dffc1) **2. Edit config.py** 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](https://mintcdn.com/cometapi/mA1ovj6s0e3RM42l/images/integrations/810968_351626.png?fit=max\&auto=format\&n=mA1ovj6s0e3RM42l\&q=85\&s=0d0043385016ec8ad0260eac8842dec4) **3. Restart and test** 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 **1. Get your CometAPI API key** 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](https://mintcdn.com/cometapi/SZhlxZhCnMLn__BW/images/overview/810968_364191.png?fit=max\&auto=format\&n=SZhlxZhCnMLn__BW\&q=85\&s=aef81a83f29f8eb16655ed4060425f50) ![CometAPI API key and base URL](https://mintcdn.com/cometapi/HhtmQffktazbxUvS/images/overview/810968_364193.png?fit=max\&auto=format\&n=HhtmQffktazbxUvS\&q=85\&s=d893f659267150d0faf45f99eb5dffc1) **2. Edit config.toml** 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](https://mintcdn.com/cometapi/mA1ovj6s0e3RM42l/images/integrations/810968_351553.png?fit=max\&auto=format\&n=mA1ovj6s0e3RM42l\&q=85\&s=07a12c20d1fe1aed2f3d1832a27e8f1d) **3. Test the connection** 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 **1. Get your CometAPI API key** 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](https://mintcdn.com/cometapi/SZhlxZhCnMLn__BW/images/overview/810968_364191.png?fit=max\&auto=format\&n=SZhlxZhCnMLn__BW\&q=85\&s=aef81a83f29f8eb16655ed4060425f50) ![CometAPI API key details with the base URL shown](https://mintcdn.com/cometapi/HhtmQffktazbxUvS/images/overview/810968_364193.png?fit=max\&auto=format\&n=HhtmQffktazbxUvS\&q=85\&s=d893f659267150d0faf45f99eb5dffc1) **2. Install Hermes Agent** 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 ``` > [!NOTE] > > 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` | > [!WARNING] > > 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). **1. Store your CometAPI key** 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. **2. Configure the OpenAI-compatible route** 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/). > [!NOTE] > > Keep the API key in `~/.hermes/.env`. Do not hardcode secrets in `config.yaml`. > [!NOTE] > > This setup configures the main chat model. Hermes can use separate auxiliary models for tasks such as vision or web extraction. **3. Configure the Claude Messages route** 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/). > [!NOTE] > > Keep `base_url` at `https://api.cometapi.com` for this route. Hermes uses the Anthropic Messages transport from the named provider. ## Verification **1. Check the configuration** 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. **2. Run a real chat test** 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 > **Clean reinstall (optional)** > > 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. > **Use hermes model instead (optional)** > > 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](https://mintcdn.com/cometapi/E4FFvyMYmaOZoldp/images/integrations/810968_360315.png?fit=max\&auto=format\&n=E4FFvyMYmaOZoldp\&q=85\&s=f922401fe2555358631fed147db49b0f) ![Immersive Translation extension installation page](https://mintcdn.com/cometapi/E4FFvyMYmaOZoldp/images/integrations/810968_360316.png?fit=max\&auto=format\&n=E4FFvyMYmaOZoldp\&q=85\&s=c504344ed770c68c806c17bca6b3084b) * A [CometAPI](https://www.cometapi.com) account with an active API key ## Setup **1. Get your CometAPI API key** 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](https://mintcdn.com/cometapi/SZhlxZhCnMLn__BW/images/overview/810968_364191.png?fit=max\&auto=format\&n=SZhlxZhCnMLn__BW\&q=85\&s=aef81a83f29f8eb16655ed4060425f50) ![CometAPI API key and base URL](https://mintcdn.com/cometapi/HhtmQffktazbxUvS/images/overview/810968_364193.png?fit=max\&auto=format\&n=HhtmQffktazbxUvS\&q=85\&s=d893f659267150d0faf45f99eb5dffc1) **2. Add CometAPI as an OpenAI-compatible service** 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](https://mintcdn.com/cometapi/mA1ovj6s0e3RM42l/images/integrations/810968_351546.png?fit=max\&auto=format\&n=mA1ovj6s0e3RM42l\&q=85\&s=e4437b20cd9e8cdbedfa0410b0cf1d3c) ![API address and key fields filled in for CometAPI](https://mintcdn.com/cometapi/mA1ovj6s0e3RM42l/images/integrations/810968_351547.png?fit=max\&auto=format\&n=mA1ovj6s0e3RM42l\&q=85\&s=75c2bc0d71731de1c0da744aa106a0d8) **3. Test the service** Click **Test Service** in the settings panel. A successful verification confirms the integration is working. ![Immersive Translation service test showing a successful result](https://mintcdn.com/cometapi/mA1ovj6s0e3RM42l/images/integrations/810968_351548.png?fit=max\&auto=format\&n=mA1ovj6s0e3RM42l\&q=85\&s=d5f341f7b99ab31d939ac1f10f5ad06f) > [!TIP] > > 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. [Claude Code Terminal coding agent](/integrations/claude-code) [Codex CLI coding agent](/integrations/codex) [Pi Terminal coding harness](/integrations/pi) DeepSeek Harness Terminal coding harness [Open](/integrations/deepseek-harness) [OpenCode Terminal coding agent](/integrations/opencode) [Gemini CLI Terminal coding tool](/integrations/gemini-cli) ## Agents Connect CometAPI to autonomous and semi-autonomous AI agent platforms. [OpenClaw Multi-provider AI agent](/integrations/openclaw) [Hermes Agent CLI AI agent](/integrations/hermes-agent) [Agno Python agent framework](/integrations/agno) [WorkBuddy AI Desktop AI agent](/integrations/workbuddy-ai) ## Chat clients Use CometAPI as a custom model provider in your preferred chat interface. [Claude Desktop Desktop chat app](/integrations/claude-desktop) [Lobe Chat Open-source chat UI](/integrations/lobe-chat) [Open WebUI Self-hosted web UI](/integrations/open-webui) ## Automation platforms Add AI capabilities to your workflows through visual automation builders. [Dify LLM app platform](/integrations/dify) [n8n Workflow automation](/integrations/n8n) [Make Visual automation](/integrations/make) [Langflow Visual agent builder](/integrations/langflow) ## Observability and evaluation Use CometAPI in observability, evaluation, and red-team workflows. [Langfuse LLM observability](/integrations/langfuse) [Promptfoo Prompt evaluation](/integrations/promptfoo) ## Frameworks Integrate CometAPI into your codebase through popular AI/ML SDKs. [AI SDK TypeScript AI toolkit](/integrations/ai-sdk) [LiteLLM Python LLM interface](/integrations/litellm) [LlamaIndex Data framework for LLM apps](/integrations/llamaindex) [LangChain LLM application framework](/integrations/langchain) # 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](https://mintcdn.com/cometapi/mA1ovj6s0e3RM42l/images/integrations/810968_352994.png?fit=max\&auto=format\&n=mA1ovj6s0e3RM42l\&q=85\&s=3ea7331394d52a903c9b550830689eef) * A [CometAPI](https://www.cometapi.com) account with an active API key ## Setup **1. Get your CometAPI API key** Log in to the [CometAPI dashboard](https://www.cometapi.com/console). Click **Add API Key** and copy your key. ![CometAPI dashboard — API keys section](https://mintcdn.com/cometapi/E4FFvyMYmaOZoldp/images/integrations/810968_360264.png?fit=max\&auto=format\&n=E4FFvyMYmaOZoldp\&q=85\&s=686b18e5eda53581cd92f39b18683c01) ![Add API Key dialog in CometAPI console](https://mintcdn.com/cometapi/E4FFvyMYmaOZoldp/images/integrations/810968_360265.png?fit=max\&auto=format\&n=E4FFvyMYmaOZoldp\&q=85\&s=4a5a528f1fbbeb3da7ace18066b73bd1) ![CometAPI API key and base URL](https://mintcdn.com/cometapi/E4FFvyMYmaOZoldp/images/integrations/810968_360266.png?fit=max\&auto=format\&n=E4FFvyMYmaOZoldp\&q=85\&s=8462dfff1cf0a880c44effc7dccbc131) **2. Configure the translation engine** 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](https://mintcdn.com/cometapi/SZhlxZhCnMLn__BW/images/overview/810968_364191.png?fit=max\&auto=format\&n=SZhlxZhCnMLn__BW\&q=85\&s=aef81a83f29f8eb16655ed4060425f50) ![CometAPI API key details](https://mintcdn.com/cometapi/HhtmQffktazbxUvS/images/overview/810968_364193.png?fit=max\&auto=format\&n=HhtmQffktazbxUvS\&q=85\&s=d893f659267150d0faf45f99eb5dffc1) **3. Test the integration** Click **Test Service** in the plugin settings. A successful verification confirms the setup is working. ![IntelliJ Translation Plugin test — successful result](https://mintcdn.com/cometapi/mA1ovj6s0e3RM42l/images/integrations/810968_352997.png?fit=max\&auto=format\&n=mA1ovj6s0e3RM42l\&q=85\&s=2acec03c1fcd4584cf8448d588cf5d68) > [!TIP] > > 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](https://mintcdn.com/cometapi/mA1ovj6s0e3RM42l/images/integrations/810968_352998.png?fit=max\&auto=format\&n=mA1ovj6s0e3RM42l\&q=85\&s=1138ce4ff04851f6db1ff996ea91f667) # 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 **1. Add the CometAPI component** In the Langflow canvas, open the component menu. Search for **CometAPI**, then add the CometAPI text generation component to your flow. **2. Enter your CometAPI API key** Select the CometAPI component. In the component inspection panel, enter your CometAPI API key in the API key field. **3. Choose a model ID** 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. **4. Connect chat input and output** 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**. **5. Test in Playground** 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 > **The CometAPI component is missing** > > 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. > **The model list does not load** > > 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. > **The flow runs but returns an error** > > 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 **1. Create a Langfuse LLM connection** In Langfuse, open **Project Settings** → **LLM Connections**. Start the flow for adding an LLM API key. **2. Choose the OpenAI adapter** Select **OpenAI** as the provider. Langfuse uses this adapter for model providers that support the OpenAI API schema. **3. Enter CometAPI credentials** 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. **4. Test in Playground** 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 > **The model is not visible in Langfuse** > > 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. > **The request uses the wrong API path** > > Use `https://api.cometapi.com/v1` as the base URL. Langfuse appends the OpenAI-compatible path for the selected adapter. > **Evaluator calls fail** > > 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 **1. Get your CometAPI API key** 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](https://mintcdn.com/cometapi/SZhlxZhCnMLn__BW/images/overview/810968_364191.png?fit=max\&auto=format\&n=SZhlxZhCnMLn__BW\&q=85\&s=aef81a83f29f8eb16655ed4060425f50) ![CometAPI API key and base URL](https://mintcdn.com/cometapi/HhtmQffktazbxUvS/images/overview/810968_364193.png?fit=max\&auto=format\&n=HhtmQffktazbxUvS\&q=85\&s=d893f659267150d0faf45f99eb5dffc1) **2. Configure the OpenAI endpoint** 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](https://mintcdn.com/cometapi/mA1ovj6s0e3RM42l/images/integrations/810968_351621.png?fit=max\&auto=format\&n=mA1ovj6s0e3RM42l\&q=85\&s=5d45cd43d93da40b2a2e0242aae24b04) ![LibreChat chat interface after CometAPI has been configured](https://mintcdn.com/cometapi/mA1ovj6s0e3RM42l/images/integrations/810968_351622.png?fit=max\&auto=format\&n=mA1ovj6s0e3RM42l\&q=85\&s=618a09316772d953db084f36234fd8d5) **3. Test the connection** 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) **1. Install LiteLLM** ```bash theme={null} pip install litellm ``` **2. Set your API key** 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 = "" ``` > [!NOTE] > > Use environment variables to avoid hardcoding sensitive credentials in your scripts. **3. Make a completion call** 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) ``` **4. Async and streaming calls** 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()) ``` > **Tips and troubleshooting** > > * **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 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 **1. Get your CometAPI API key** Log in to the [CometAPI dashboard](https://www.cometapi.com/console). Click **Add API Key** and copy your key. ![CometAPI dashboard — Add API Key](https://mintcdn.com/cometapi/SZhlxZhCnMLn__BW/images/overview/810968_364191.png?fit=max\&auto=format\&n=SZhlxZhCnMLn__BW\&q=85\&s=aef81a83f29f8eb16655ed4060425f50) ![CometAPI API key and base URL](https://mintcdn.com/cometapi/HhtmQffktazbxUvS/images/overview/810968_364193.png?fit=max\&auto=format\&n=HhtmQffktazbxUvS\&q=85\&s=d893f659267150d0faf45f99eb5dffc1) **2. Select CometAPI as the model provider** 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](https://mintcdn.com/cometapi/E4FFvyMYmaOZoldp/images/integrations/810968_360319.png?fit=max\&auto=format\&n=E4FFvyMYmaOZoldp\&q=85\&s=299c123baafc43c598449113a6723031) ![CometAPI provider settings in Lobe-Chat with API key entered](https://mintcdn.com/cometapi/SZhlxZhCnMLn__BW/images/integrations/810968_361341.png?fit=max\&auto=format\&n=SZhlxZhCnMLn__BW\&q=85\&s=dc0b478e91393dcb3a5db92f07360ece) **3. Test the connection** 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](https://mintcdn.com/cometapi/SZhlxZhCnMLn__BW/images/integrations/810968_361342.png?fit=max\&auto=format\&n=SZhlxZhCnMLn__BW\&q=85\&s=5f804dee6dc6ac724164630e945a053d) ![Lobe-Chat model response panel](https://mintcdn.com/cometapi/SZhlxZhCnMLn__BW/images/integrations/810968_361343.png?fit=max\&auto=format\&n=SZhlxZhCnMLn__BW\&q=85\&s=3bdff04efc655f5235d11f34cb43b1b3) # 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) **1. Get your CometAPI API key** 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](https://mintcdn.com/cometapi/SZhlxZhCnMLn__BW/images/overview/810968_364191.png?fit=max\&auto=format\&n=SZhlxZhCnMLn__BW\&q=85\&s=aef81a83f29f8eb16655ed4060425f50) ![CometAPI API key details with base URL](https://mintcdn.com/cometapi/HhtmQffktazbxUvS/images/overview/810968_364193.png?fit=max\&auto=format\&n=HhtmQffktazbxUvS\&q=85\&s=d893f659267150d0faf45f99eb5dffc1) **2. Add CometAPI to a scenario** In Make, click **Create scenario**. In the scenario editor, click the **+** icon and search for **CometAPI**. ![Make scenario editor with the module search open](https://mintcdn.com/cometapi/E4FFvyMYmaOZoldp/images/integrations/810968_360356.png?fit=max\&auto=format\&n=E4FFvyMYmaOZoldp\&q=85\&s=9a7600888fe9833ac94ab3dc1df47434) ![Make search results showing the CometAPI module](https://mintcdn.com/cometapi/E4FFvyMYmaOZoldp/images/integrations/810968_360357.png?fit=max\&auto=format\&n=E4FFvyMYmaOZoldp\&q=85\&s=45186c2db38fa62e2a1592ec722b044a) **3. Connect your CometAPI account** 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](https://mintcdn.com/cometapi/SZhlxZhCnMLn__BW/images/integrations/810968_360358.png?fit=max\&auto=format\&n=SZhlxZhCnMLn__BW\&q=85\&s=260de8318fa33dc6100ac98b8a2c9c34) **4. Configure the API call** 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](https://mintcdn.com/cometapi/SZhlxZhCnMLn__BW/images/integrations/810968_360359.png?fit=max\&auto=format\&n=SZhlxZhCnMLn__BW\&q=85\&s=951565cb41ecc00937654a7c418a9ec3) **5. Test and publish** 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](https://mintcdn.com/cometapi/SZhlxZhCnMLn__BW/images/integrations/810968_360369.png?fit=max\&auto=format\&n=SZhlxZhCnMLn__BW\&q=85\&s=4bc0c56e0e80a8d9b60af213a5f7ecf3) ![Make scenario run history showing success](https://mintcdn.com/cometapi/SZhlxZhCnMLn__BW/images/integrations/810968_360370.png?fit=max\&auto=format\&n=SZhlxZhCnMLn__BW\&q=85\&s=c2193af570a299525216ec10bd0ee008) If the call fails, verify your API key and endpoint URL, or contact [CometAPI support](https://www.cometapi.com). > [!TIP] > > 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 > [!NOTE] > > For local/self-hosted n8n with the CometAPI community node, see the [n8n Local Deployment](/integrations/n8n-local-deployment) guide. ## Setup **1. Get your CometAPI API key** 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](https://mintcdn.com/cometapi/SZhlxZhCnMLn__BW/images/overview/810968_364191.png?fit=max\&auto=format\&n=SZhlxZhCnMLn__BW\&q=85\&s=aef81a83f29f8eb16655ed4060425f50) ![CometAPI API key and base URL](https://mintcdn.com/cometapi/HhtmQffktazbxUvS/images/overview/810968_364193.png?fit=max\&auto=format\&n=HhtmQffktazbxUvS\&q=85\&s=d893f659267150d0faf45f99eb5dffc1) **2. Create an OpenAI credential** 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](https://mintcdn.com/cometapi/mA1ovj6s0e3RM42l/images/integrations/810968_354031.png?fit=max\&auto=format\&n=mA1ovj6s0e3RM42l\&q=85\&s=915bfac17a897d2df0a6868a71fd1618) ![n8n OpenAI credential form with CometAPI key and base URL filled in](https://mintcdn.com/cometapi/mA1ovj6s0e3RM42l/images/integrations/810968_354032.png?fit=max\&auto=format\&n=mA1ovj6s0e3RM42l\&q=85\&s=c94c58a1f8826554f7b703d376c3ce53) ![n8n credential saved successfully](https://mintcdn.com/cometapi/mA1ovj6s0e3RM42l/images/integrations/810968_354037.png?fit=max\&auto=format\&n=mA1ovj6s0e3RM42l\&q=85\&s=e46a7e333b897ec09a791a26bb8db13f) **3. Test the connection** 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](https://mintcdn.com/cometapi/mA1ovj6s0e3RM42l/images/integrations/810968_354039.png?fit=max\&auto=format\&n=mA1ovj6s0e3RM42l\&q=85\&s=4707697d418bff1dec20eb42dd5a2c60) # 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) **1. Get your CometAPI API key** 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](https://mintcdn.com/cometapi/SZhlxZhCnMLn__BW/images/overview/810968_364191.png?fit=max\&auto=format\&n=SZhlxZhCnMLn__BW\&q=85\&s=aef81a83f29f8eb16655ed4060425f50) ![CometAPI API key details with base URL](https://mintcdn.com/cometapi/HhtmQffktazbxUvS/images/overview/810968_364193.png?fit=max\&auto=format\&n=HhtmQffktazbxUvS\&q=85\&s=d893f659267150d0faf45f99eb5dffc1) **2. Install Node.js via nvm** 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 ``` > [!NOTE] > > If you see `n8n: command not found` later, restart the terminal or ensure the nvm-managed npm global bin directory is on your `PATH`. **3. Install and start n8n** ```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](https://mintcdn.com/cometapi/SZhlxZhCnMLn__BW/images/integrations/810968_360463.png?fit=max\&auto=format\&n=SZhlxZhCnMLn__BW\&q=85\&s=80fe6068a8af4ec3b3503ff41d378a17) ![n8n startup logs in the terminal](https://mintcdn.com/cometapi/SZhlxZhCnMLn__BW/images/integrations/810968_360464.png?fit=max\&auto=format\&n=SZhlxZhCnMLn__BW\&q=85\&s=77cadfd218dbe0fef19fe701550ea363) **4. Create your owner account** 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](https://mintcdn.com/cometapi/SZhlxZhCnMLn__BW/images/integrations/810968_360465.png?fit=max\&auto=format\&n=SZhlxZhCnMLn__BW\&q=85\&s=8fdd100138f2bf01bbf834d9db1ea29e) **5. Install the CometAPI community node** 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](https://mintcdn.com/cometapi/SZhlxZhCnMLn__BW/images/integrations/810968_360467.png?fit=max\&auto=format\&n=SZhlxZhCnMLn__BW\&q=85\&s=1c107922e16332157d278bf834b3e32a) ![Install dialog with the CometAPI package name entered](https://mintcdn.com/cometapi/SZhlxZhCnMLn__BW/images/integrations/810968_360468.png?fit=max\&auto=format\&n=SZhlxZhCnMLn__BW\&q=85\&s=98c05d77cb6adf333052b4d5014fc506) > [!NOTE] > > 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. **6. Create a workflow and configure credentials** 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](https://mintcdn.com/cometapi/SZhlxZhCnMLn__BW/images/integrations/810968_360469.png?fit=max\&auto=format\&n=SZhlxZhCnMLn__BW\&q=85\&s=b47e1304ec3165720dd3ef37e1429485) ![CometAPI node added to the n8n canvas](https://mintcdn.com/cometapi/SZhlxZhCnMLn__BW/images/integrations/810968_360472.png?fit=max\&auto=format\&n=SZhlxZhCnMLn__BW\&q=85\&s=b765a2d8024f4c5d36305916c440d02f) 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](https://mintcdn.com/cometapi/SZhlxZhCnMLn__BW/images/integrations/810968_360474.png?fit=max\&auto=format\&n=SZhlxZhCnMLn__BW\&q=85\&s=deee1c999cbfb2c432daaa53904d6b38) 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](https://mintcdn.com/cometapi/SZhlxZhCnMLn__BW/images/integrations/810968_360471.png?fit=max\&auto=format\&n=SZhlxZhCnMLn__BW\&q=85\&s=6953b97533f02e4f50cb1f0490ff057d) > **Troubleshooting** > > * **`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 **1. Get your CometAPI API key** 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](https://mintcdn.com/cometapi/SZhlxZhCnMLn__BW/images/overview/810968_364191.png?fit=max\&auto=format\&n=SZhlxZhCnMLn__BW\&q=85\&s=aef81a83f29f8eb16655ed4060425f50) ![CometAPI API key and base URL](https://mintcdn.com/cometapi/HhtmQffktazbxUvS/images/overview/810968_364193.png?fit=max\&auto=format\&n=HhtmQffktazbxUvS\&q=85\&s=d893f659267150d0faf45f99eb5dffc1) **2. Configure the API endpoint** 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](https://mintcdn.com/cometapi/mA1ovj6s0e3RM42l/images/integrations/810968_351592.png?fit=max\&auto=format\&n=mA1ovj6s0e3RM42l\&q=85\&s=9e22a16aa7ddec68fcbbecb8ef28c2e6) **3. Test the connection** Send a test message. A successful reply confirms the integration is working. > [!TIP] > > 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](https://mintcdn.com/cometapi/mA1ovj6s0e3RM42l/images/integrations/810968_351619.png?fit=max\&auto=format\&n=mA1ovj6s0e3RM42l\&q=85\&s=9af2d4efbd3b18ecec26c6e43a83f650) * A [CometAPI](https://www.cometapi.com) account with an active API key ## Setup **1. Get your CometAPI API key** 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](https://mintcdn.com/cometapi/SZhlxZhCnMLn__BW/images/overview/810968_364191.png?fit=max\&auto=format\&n=SZhlxZhCnMLn__BW\&q=85\&s=aef81a83f29f8eb16655ed4060425f50) ![CometAPI API key and base URL](https://mintcdn.com/cometapi/HhtmQffktazbxUvS/images/overview/810968_364193.png?fit=max\&auto=format\&n=HhtmQffktazbxUvS\&q=85\&s=d893f659267150d0faf45f99eb5dffc1) **2. Configure the API connection** 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](https://mintcdn.com/cometapi/mA1ovj6s0e3RM42l/images/integrations/810968_351620.png?fit=max\&auto=format\&n=mA1ovj6s0e3RM42l\&q=85\&s=b8a4bc38eb8e1ba0da8cb30e3fe728e5) **3. Test the connection** 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 **1. Get your CometAPI API key** 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](https://mintcdn.com/cometapi/SZhlxZhCnMLn__BW/images/overview/810968_364191.png?fit=max\&auto=format\&n=SZhlxZhCnMLn__BW\&q=85\&s=aef81a83f29f8eb16655ed4060425f50) ![CometAPI API key and base URL](https://mintcdn.com/cometapi/HhtmQffktazbxUvS/images/overview/810968_364193.png?fit=max\&auto=format\&n=HhtmQffktazbxUvS\&q=85\&s=d893f659267150d0faf45f99eb5dffc1) **2. Add an external OpenAI connection** 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](https://mintcdn.com/cometapi/mA1ovj6s0e3RM42l/images/integrations/810968_351624.png?fit=max\&auto=format\&n=mA1ovj6s0e3RM42l\&q=85\&s=4878931888f1deeda5365545bc35a01a) ![Open WebUI settings saved with CometAPI connection active](https://mintcdn.com/cometapi/mA1ovj6s0e3RM42l/images/integrations/810968_351625.png?fit=max\&auto=format\&n=mA1ovj6s0e3RM42l\&q=85\&s=40e7df7cb60b43a4b585ededa36847f2) **3. Test the connection** 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 **1. Get your CometAPI API key** 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](https://mintcdn.com/cometapi/SZhlxZhCnMLn__BW/images/overview/810968_364191.png?fit=max\&auto=format\&n=SZhlxZhCnMLn__BW\&q=85\&s=aef81a83f29f8eb16655ed4060425f50) ![CometAPI API key and base URL](https://mintcdn.com/cometapi/HhtmQffktazbxUvS/images/overview/810968_364193.png?fit=max\&auto=format\&n=HhtmQffktazbxUvS\&q=85\&s=d893f659267150d0faf45f99eb5dffc1) **2. Configure the API provider** 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](https://mintcdn.com/cometapi/mA1ovj6s0e3RM42l/images/integrations/810968_351576.png?fit=max\&auto=format\&n=mA1ovj6s0e3RM42l\&q=85\&s=c7b5e6b50d97dc3b7c26a7254f6642a7) **3. Test the translation** Select some text and trigger a translation. A successful result confirms the integration is working. > [!TIP] > > 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](https://mintcdn.com/cometapi/mA1ovj6s0e3RM42l/images/integrations/810968_351577.png?fit=max\&auto=format\&n=mA1ovj6s0e3RM42l\&q=85\&s=620c2aa95b307cd69cb2d657547e2e83) # Use OpenClaw with CometAPI Source: https://apidoc.cometapi.com/integrations/openclaw Use this guide to configure OpenClaw with CometAPI through Chat Completions, Responses, Anthropic Messages, or Google Generative AI. Use this guide to connect [OpenClaw](https://openclaw.ai) to CometAPI. Choose one API format and model ID for the first configuration. > [!NOTE] > > OpenClaw v2026.8.1 is also branded OpenClaw 2.0. The package does not use a > `2.x` version number. See the > [OpenClaw 2.0 announcement](https://openclaw.ai/blog/openclaw-2-accidentally) > and the [v2026.8.1 release notes](https://docs.openclaw.ai/releases/2026.8.1). Official OpenClaw references: * [Installation](https://docs.openclaw.ai/install) * [Updating](https://docs.openclaw.ai/install/updating) * [Onboarding](https://docs.openclaw.ai/start/onboarding-overview) * [Custom provider configuration](https://docs.openclaw.ai/gateway/config-tools) * [Environment variables and SecretRef](https://docs.openclaw.ai/help/environment) ## Prerequisites * Node.js 22.22.3+, 24.15+, or 25.9+. Node 26 is recommended. Node 23 is not supported. * A CometAPI account with an active API key from the [dashboard](https://www.cometapi.com/console/token). * A model ID from the [CometAPI Models page](/overview/models). ## Installation and upgrades **First installation** The official installer can install the CLI without starting onboarding. This keeps model configuration as a separate step. **macOS / Linux / WSL2** The following command runs the official installer: ```bash theme={null} curl -fsSL https://openclaw.ai/install.sh \ | bash -s -- --no-onboard ``` **Windows PowerShell** The following command runs the official PowerShell installer: ```powershell theme={null} & ([scriptblock]::Create( (iwr -useb https://openclaw.ai/install.ps1) )) -NoOnboard ``` If you manage Node.js and npm yourself, npm 11.16+ and npm 12 accept the `--allow-scripts` option. The following command installs OpenClaw without starting onboarding: ```bash theme={null} npm install -g openclaw@latest --allow-scripts=openclaw ``` On npm 11.15 and earlier, omit `--allow-scripts=openclaw` because that npm version does not recognize the option. Confirm that the installed CLI meets the minimum version for this guide: ```bash theme={null} openclaw --version ``` Continue to [Configure CometAPI](#configure-cometapi). Do not run plain onboarding first, because the guided flow does not expose every custom API adapter. **Upgrade an installation** Create and verify a backup before a significant update. The archive can contain API keys, channel state, and authentication data, so protect it as you protect the OpenClaw state directory. The following commands create the backup and update OpenClaw: ```bash theme={null} mkdir -p ~/Backups/openclaw openclaw backup create --output ~/Backups/openclaw --verify openclaw update ``` After the update, repair supported migrations and check Gateway health: ```bash theme={null} openclaw doctor --fix openclaw gateway restart openclaw health ``` An update preserves the configured model route. Do not repeat onboarding unless you want to change the model provider or its authentication. ## Configure CometAPI ### Use classic onboarding Classic onboarding is the preferred first-installation path for Chat Completions, Responses, and Anthropic Messages. The following command opens classic onboarding and installs the background service: ```bash theme={null} openclaw onboard --classic --install-daemon ``` In **Model/Auth**, choose **Custom Provider**. Then enter the values for one of these compatibility options: | API format | Provider ID | Compatibility option | Base URL | | - | - | - | - | | Chat Completions | `cometapi-openai` | **OpenAI-compatible** | `https://api.cometapi.com/v1` | | Responses | `cometapi-openai-responses` | **OpenAI Responses-compatible** | `https://api.cometapi.com/v1` | | Anthropic Messages | `cometapi-claude` | **Anthropic-compatible** | `https://api.cometapi.com` | Enter the matching provider ID, `your-model-id`, and your CometAPI API key when prompted. The terminal wizard masks the API key input. The classic Custom Provider menu does not include the Google Generative AI adapter. To use that adapter, complete [Configure a provider with config commands](#configure-a-provider-with-config-commands), set the primary model, and then run classic onboarding. Choose **Keep existing model config** when the wizard presents that option. ### Configure a provider with config commands Use this path for the Google adapter or for controlled configuration changes. OpenClaw supports JSON5, so do not parse and rewrite `openclaw.json` with a strict JSON tool. > [!WARNING] > > OpenClaw's native config writer validates JSON5 but normalizes the file to > JSON when it writes. Existing comments, trailing commas, and formatting may > be removed. Create a verified backup before applying a patch if those details > are important to you. First, print the active config path and validate its content: ```bash theme={null} openclaw config file openclaw config validate ``` OpenClaw reads provider API keys from the process environment or the global state `.env` file. It does not trust a workspace `.env` file for provider API keys. The global file is `~/.openclaw/.env`, or `$OPENCLAW_STATE_DIR/.env` when `OPENCLAW_STATE_DIR` is set. If classic onboarding stored the API key, skip the following step. Otherwise, use the tab for your operating system to store the API key without displaying it. **macOS / Linux / WSL2** The following commands update `COMETAPI_KEY` atomically and reject an empty value: ```bash theme={null} state_dir="${OPENCLAW_STATE_DIR:-$HOME/.openclaw}" install -d -m 700 "$state_dir" read -rsp "CometAPI API key: " COMETAPI_KEY printf '\n' if [ -z "$COMETAPI_KEY" ]; then echo "The CometAPI API key cannot be empty." >&2 unset COMETAPI_KEY exit 1 fi umask 077 env_file="$state_dir/.env" temp_file="$(mktemp "${env_file}.XXXXXX")" if [ -f "$env_file" ]; then awk -F= '$1 != "COMETAPI_KEY"' "$env_file" > "$temp_file" fi printf 'COMETAPI_KEY=%s\n' "$COMETAPI_KEY" >> "$temp_file" chmod 600 "$temp_file" mv "$temp_file" "$env_file" unset COMETAPI_KEY temp_file env_file state_dir ``` **Windows PowerShell** The following commands update `COMETAPI_KEY` without displaying it: ```powershell theme={null} $stateDir = if ($env:OPENCLAW_STATE_DIR) { $env:OPENCLAW_STATE_DIR } else { Join-Path $HOME ".openclaw" } New-Item -ItemType Directory -Force -Path $stateDir | Out-Null $secureKey = Read-Host "CometAPI API key" -AsSecureString $plainKey = [Net.NetworkCredential]::new("", $secureKey).Password if ([string]::IsNullOrWhiteSpace($plainKey)) { throw "The CometAPI API key cannot be empty." } $envFile = Join-Path $stateDir ".env" $lines = @() if (Test-Path $envFile) { $lines = @(Get-Content $envFile | Where-Object { $_ -notmatch '^COMETAPI_KEY=' }) } $lines += "COMETAPI_KEY=$plainKey" $tempFile = Join-Path $stateDir ".$([guid]::NewGuid()).tmp" [IO.File]::WriteAllLines($tempFile, $lines) Move-Item -Force $tempFile $envFile $plainKey = $null $secureKey = $null ``` Before you add a provider, inspect its target path. Replace the provider ID in the following command with the ID from your selected tab: ```bash theme={null} openclaw config get models.providers.cometapi-openai --json ``` If the command returns a configured provider, stop before applying the example. `config patch` merges objects, but it replaces arrays. Merge the new model into the provider's model array before you write that array. This preserves model metadata, custom headers, and other provider settings. Choose one API format. Each patch uses an environment-backed SecretRef, changes only the target config paths, and keeps other config sections intact. > [!WARNING] > > A model ID is not automatically compatible with every API adapter. Select an > adapter that the exact CometAPI model and route support, then verify that > provider/model/adapter combination with a live request. The > `your-model-id` value below is a configuration placeholder, not a universal > compatibility claim. **Chat Completions** * Provider ID: `cometapi-openai` * OpenClaw adapter: `openai-completions` * Base URL: `https://api.cometapi.com/v1` * Primary model reference: `cometapi-openai/your-model-id` Create `cometapi.patch.json5` with this provider patch: ```json5 theme={null} { models: { mode: "merge", providers: { "cometapi-openai": { baseUrl: "https://api.cometapi.com/v1", apiKey: { source: "env", provider: "default", id: "COMETAPI_KEY", }, api: "openai-completions", models: [ { id: "your-model-id", name: "CometAPI model", input: ["text"], }, ], }, }, }, } ``` Validate the patch before OpenClaw writes the config: ```bash theme={null} openclaw config patch --file ./cometapi.patch.json5 --dry-run ``` If validation succeeds, apply the same patch: ```bash theme={null} openclaw config patch --file ./cometapi.patch.json5 ``` If no primary model is configured, set this model as the default: ```bash theme={null} openclaw models set cometapi-openai/your-model-id ``` Verify the provider configuration and send a minimal model request: ```bash theme={null} openclaw models list --provider cometapi-openai openclaw models status --probe \ --probe-provider cometapi-openai openclaw agent exec \ "Reply exactly with: OPENCLAW_OK" \ --model cometapi-openai/your-model-id \ --thinking off \ --json ``` To switch the active OpenClaw chat session, run this chat command: ```text theme={null} /model cometapi-openai/your-model-id ``` **Responses** * Provider ID: `cometapi-openai-responses` * OpenClaw adapter: `openai-responses` * Base URL: `https://api.cometapi.com/v1` * Primary model reference: `cometapi-openai-responses/your-model-id` Create `cometapi.patch.json5` with this provider patch: ```json5 theme={null} { models: { mode: "merge", providers: { "cometapi-openai-responses": { baseUrl: "https://api.cometapi.com/v1", apiKey: { source: "env", provider: "default", id: "COMETAPI_KEY", }, api: "openai-responses", models: [ { id: "your-model-id", name: "CometAPI model", input: ["text"], }, ], }, }, }, } ``` Validate the patch before OpenClaw writes the config: ```bash theme={null} openclaw config patch --file ./cometapi.patch.json5 --dry-run ``` If validation succeeds, apply the same patch: ```bash theme={null} openclaw config patch --file ./cometapi.patch.json5 ``` If no primary model is configured, set this model as the default: ```bash theme={null} openclaw models set cometapi-openai-responses/your-model-id ``` Verify the provider configuration and send a minimal model request: ```bash theme={null} openclaw models list --provider cometapi-openai-responses openclaw models status --probe \ --probe-provider cometapi-openai-responses openclaw agent exec \ "Reply exactly with: OPENCLAW_OK" \ --model cometapi-openai-responses/your-model-id \ --thinking off \ --json ``` To switch the active OpenClaw chat session, run this chat command: ```text theme={null} /model cometapi-openai-responses/your-model-id ``` **Anthropic Messages** * Provider ID: `cometapi-claude` * OpenClaw adapter: `anthropic-messages` * Base URL: `https://api.cometapi.com` * Primary model reference: `cometapi-claude/your-model-id` Create `cometapi.patch.json5` with this provider patch: ```json5 theme={null} { models: { mode: "merge", providers: { "cometapi-claude": { baseUrl: "https://api.cometapi.com", apiKey: { source: "env", provider: "default", id: "COMETAPI_KEY", }, api: "anthropic-messages", models: [ { id: "your-model-id", name: "CometAPI model", input: ["text"], }, ], }, }, }, } ``` Validate the patch before OpenClaw writes the config: ```bash theme={null} openclaw config patch --file ./cometapi.patch.json5 --dry-run ``` If validation succeeds, apply the same patch: ```bash theme={null} openclaw config patch --file ./cometapi.patch.json5 ``` If no primary model is configured, set this model as the default: ```bash theme={null} openclaw models set cometapi-claude/your-model-id ``` Verify the provider configuration and send a minimal model request: ```bash theme={null} openclaw models list --provider cometapi-claude openclaw models status --probe \ --probe-provider cometapi-claude openclaw agent exec \ "Reply exactly with: OPENCLAW_OK" \ --model cometapi-claude/your-model-id \ --thinking off \ --json ``` To switch the active OpenClaw chat session, run this chat command: ```text theme={null} /model cometapi-claude/your-model-id ``` **Google Generative AI** * Provider ID: `cometapi-google` * OpenClaw adapter: `google-generative-ai` * Base URL: `https://api.cometapi.com/v1beta` * Primary model reference: `cometapi-google/your-model-id` Create `cometapi.patch.json5` with this provider patch: ```json5 theme={null} { models: { mode: "merge", providers: { "cometapi-google": { baseUrl: "https://api.cometapi.com/v1beta", apiKey: { source: "env", provider: "default", id: "COMETAPI_KEY", }, api: "google-generative-ai", models: [ { id: "your-model-id", name: "CometAPI model", input: ["text"], }, ], }, }, }, } ``` Validate the patch before OpenClaw writes the config: ```bash theme={null} openclaw config patch --file ./cometapi.patch.json5 --dry-run ``` If validation succeeds, apply the same patch: ```bash theme={null} openclaw config patch --file ./cometapi.patch.json5 ``` If no primary model is configured, set this model as the default: ```bash theme={null} openclaw models set cometapi-google/your-model-id ``` Verify the provider configuration and send a minimal model request: ```bash theme={null} openclaw models list --provider cometapi-google openclaw models status --probe \ --probe-provider cometapi-google openclaw agent exec \ "Reply exactly with: OPENCLAW_OK" \ --model cometapi-google/your-model-id \ --thinking off \ --json ``` To switch the active OpenClaw chat session, run this chat command: ```text theme={null} /model cometapi-google/your-model-id ``` > [!NOTE] > > If a configuration already uses the `cometapi-gemini` provider ID, keep > that ID and use it in model references and commands. Do not rename it or > create a duplicate provider only to match this guide. ![OpenClaw 2026.8.1 model list with four CometAPI provider formats](https://mintcdn.com/cometapi/3TtEd_8hOqV-RF7y/images/integrations/810968_371721.png?fit=max\&auto=format\&n=3TtEd_8hOqV-RF7y\&q=85\&s=886471608e9cfdc3b0bc08c8582fc772) For a new provider, `openclaw config set` provides the same schema and SecretRef checks. Use `--strict-json`, `--merge`, and `--dry-run` before the write. The following alternative previews the Chat Completions provider: ```bash theme={null} openclaw config set models.providers.cometapi-openai \ '{ "baseUrl": "https://api.cometapi.com/v1", "apiKey": { "source": "env", "provider": "default", "id": "COMETAPI_KEY" }, "api": "openai-completions", "models": [ { "id": "your-model-id", "name": "CometAPI model", "input": ["text"] } ] }' \ --strict-json --merge --dry-run ``` If the dry run succeeds, repeat the command without `--dry-run` to save it. Do not apply this example to a configured provider. The `models` array must include the provider's complete merged model list before a write. ### Understand model metadata The minimal patches declare a text-only model. Add optional metadata only when you have verified the model's specifications: | Field | Effect | | - | - | | `input` | Declares accepted input modalities. Use `["text", "image"]` only when the model accepts native image input. | | `contextWindow` | Records the model's native context-window capacity. | | `contextTokens` | Limits the active input budget without changing `contextWindow`. | | `maxTokens` | Limits the output tokens that OpenClaw requests from the model. | Incorrect values can hide supported inputs, overstate the usable context, or request an unsupported output size. Keep `your-model-id` in reusable examples, and use the [CometAPI Models page](/overview/models) to select a model ID. ## Verify the complete setup After the config or global `.env` file changes, restart the Gateway: ```bash theme={null} openclaw gateway restart ``` Then validate the config and Gateway state: ```bash theme={null} openclaw config validate openclaw doctor openclaw health ``` Run the provider-specific commands from the selected API-format tab. A model list or status check confirms configuration only. The `openclaw agent exec` command sends a real model request. Confirm that it returns `OPENCLAW_OK` without an unresolved authentication, adapter, or model error. If OpenClaw retries a request, record and inspect every attempt instead of treating the final marker as single-attempt success. ## Troubleshooting > **The API key is missing** > > Confirm that `COMETAPI_KEY` is present in the process environment or the > global state `.env` file. Do not print the value into terminal output. > > After you correct the trusted key source, restart and check the Gateway: > > ```bash theme={null} > openclaw gateway restart > openclaw health > ``` > **A provider ID has different settings** > > Do not overwrite a provider that has a different `baseUrl`, `api`, custom > headers, or model metadata. Inspect the target provider first: > > ```bash theme={null} > openclaw config get models.providers.cometapi-openai --json > openclaw config validate > ``` > > Use a different provider ID when both configurations are intentional. If > the difference is accidental, create a verified backup before you change > the target provider. > **An update did not finish** > > Inspect update state before you repair the installation: > > ```bash theme={null} > openclaw update status --json > openclaw update repair > openclaw doctor --fix > openclaw health > ``` > > These commands preserve the state directory. > **A code rollback is required** > > Reinstall a known package version while you keep the state directory. First, > preview the operation: > > ```bash theme={null} > openclaw update --tag 2026.8.1 --dry-run > ``` > > If the preview is correct, run the same operation without `--dry-run`: > > ```bash theme={null} > openclaw update --tag 2026.8.1 > openclaw doctor --fix > openclaw health > ``` > > Restore a state backup only when the installed code cannot read the state. > A state restore can discard sessions and configuration changes that were > created after the backup. # 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/) > [!NOTE] > > 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 **1. Install 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. **2. Set your CometAPI API key** Store your CometAPI API key in the `COMETAPI_KEY` environment variable. **macOS / Linux / WSL** 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 ``` **Windows PowerShell** 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. **3. Choose a configuration location** 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. **4. Add the CometAPI providers** 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`. > [!WARNING] > > 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. **5. Select and verify each provider** 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 > **OpenCode does not show a CometAPI model** > > 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. > **OpenCode reports an API key or authentication error** > > 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. > **A model ID is unavailable** > > 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. > **Requests use an incorrect path** > > Keep `baseURL` at `/v1` for Chat Completions, Responses, and Messages. Use > `/v1beta` for Gemini. Do not include an operation path in `baseURL`. > **One provider works but another provider fails** > > Use a model ID that accepts the selected provider's API format. Do not > assume that one model ID accepts all four formats. > **The project configuration changes a global provider** > > 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 has more access than expected** > > 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 **1. Get your CometAPI API key** 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](https://mintcdn.com/cometapi/SZhlxZhCnMLn__BW/images/overview/810968_364191.png?fit=max\&auto=format\&n=SZhlxZhCnMLn__BW\&q=85\&s=aef81a83f29f8eb16655ed4060425f50) ![CometAPI API key and base URL](https://mintcdn.com/cometapi/HhtmQffktazbxUvS/images/overview/810968_364193.png?fit=max\&auto=format\&n=HhtmQffktazbxUvS\&q=85\&s=d893f659267150d0faf45f99eb5dffc1) **2. Create and edit config.toml** 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](https://mintcdn.com/cometapi/mA1ovj6s0e3RM42l/images/integrations/810968_351746.png?fit=max\&auto=format\&n=mA1ovj6s0e3RM42l\&q=85\&s=b54eb16e49f5d2d492107cc15dc3c601) **3. Test the connection** Run OpenManus with a test task. A successful response confirms the setup is working. ![OpenManus terminal showing a successful response from CometAPI](https://mintcdn.com/cometapi/mA1ovj6s0e3RM42l/images/integrations/810968_351747.png?fit=max\&auto=format\&n=mA1ovj6s0e3RM42l\&q=85\&s=53c1f9af9ba67a486f06287ce15c0513) # 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) > [!NOTE] > > 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 **1. Install Pi** 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 ``` **2. Set your CometAPI API key** 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. **3. Add CometAPI providers to models.json** 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. **4. Verify both providers** 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 > **Pi does not show the CometAPI model** > > 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. > **Pi reports that no API key is available** > > 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. > **Requests fail because of the base URL** > > 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. > **Pi fails before sending a model request** > > Check your Node.js version with `node --version`. The Pi package requires Node.js `>=22.19.0`. > **The model works on one route but not the other** > > 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 has more access than expected** > > 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/) **1. Get your CometAPI API key** 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](https://mintcdn.com/cometapi/SZhlxZhCnMLn__BW/images/overview/810968_364191.png?fit=max\&auto=format\&n=SZhlxZhCnMLn__BW\&q=85\&s=aef81a83f29f8eb16655ed4060425f50) ![CometAPI API key details with base URL](https://mintcdn.com/cometapi/HhtmQffktazbxUvS/images/overview/810968_364193.png?fit=max\&auto=format\&n=HhtmQffktazbxUvS\&q=85\&s=d893f659267150d0faf45f99eb5dffc1) **2. Add OpenAI service in Pot** Open Pot's menu, go to **Service Settings → Add Built-in Service**, select **OpenAI**, and enable **Stream Output**. ![Pot service settings panel](https://mintcdn.com/cometapi/E4FFvyMYmaOZoldp/images/integrations/810968_360328.png?fit=max\&auto=format\&n=E4FFvyMYmaOZoldp\&q=85\&s=09610d2bdcb807597f9231425f362f33) ![Selecting OpenAI service with stream enabled](https://mintcdn.com/cometapi/E4FFvyMYmaOZoldp/images/integrations/810968_360329.png?fit=max\&auto=format\&n=E4FFvyMYmaOZoldp\&q=85\&s=c56778e30c7e45b4846c29f032f31234) **3. Enter your API credentials** * **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](https://mintcdn.com/cometapi/E4FFvyMYmaOZoldp/images/integrations/810968_360330.png?fit=max\&auto=format\&n=E4FFvyMYmaOZoldp\&q=85\&s=dde9ce700ffb17506a9ea8b7331cee1a) **4. Test the translation** Select any text and trigger a translation. A successful response confirms the integration is working. ![Pot showing a successful AI translation result](https://mintcdn.com/cometapi/E4FFvyMYmaOZoldp/images/integrations/810968_360331.png?fit=max\&auto=format\&n=E4FFvyMYmaOZoldp\&q=85\&s=1c9343d3f829d67bf19214754eae1a67) If the call fails, double-check your API key and the endpoint URL, or contact [CometAPI support](https://www.cometapi.com). > [!TIP] > > 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 **1. Set your CometAPI API key** Set `COMETAPI_KEY` before you run evaluations: ```bash theme={null} read -rsp "CometAPI API key: " COMETAPI_KEY printf '\n' export COMETAPI_KEY ``` **2. Choose a provider format** 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. **3. Run a CLI evaluation** 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 ``` **4. Create a Promptfoo config file** 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 > **Promptfoo cannot find the API key** > > Confirm that `COMETAPI_KEY` is exported in the same shell session that runs `promptfoo eval`. > **The provider type does not match the model** > > Use `chat` for conversational and multimodal models, `embedding` for embedding models, and `image` for image generation models. > **The model ID fails** > > 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) **1. Get your CometAPI API key** 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](https://mintcdn.com/cometapi/SZhlxZhCnMLn__BW/images/overview/810968_364191.png?fit=max\&auto=format\&n=SZhlxZhCnMLn__BW\&q=85\&s=aef81a83f29f8eb16655ed4060425f50) ![CometAPI API key details with base URL](https://mintcdn.com/cometapi/HhtmQffktazbxUvS/images/overview/810968_364193.png?fit=max\&auto=format\&n=HhtmQffktazbxUvS\&q=85\&s=d893f659267150d0faf45f99eb5dffc1) **2. Configure ChatGPT Friend** 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](https://mintcdn.com/cometapi/mA1ovj6s0e3RM42l/images/integrations/810968_351617.png?fit=max\&auto=format\&n=mA1ovj6s0e3RM42l\&q=85\&s=007fd1da30f9ca6c807caf2d01205422) **3. Test the connection** 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](https://mintcdn.com/cometapi/mA1ovj6s0e3RM42l/images/integrations/810968_351618.png?fit=max\&auto=format\&n=mA1ovj6s0e3RM42l\&q=85\&s=2f2aecbecc80d2f3042f84d8e9d13d48) If the call fails, verify your API key and the interface address, or contact [CometAPI support](https://www.cometapi.com). # Use WorkBuddy AI with CometAPI Source: https://apidoc.cometapi.com/integrations/workbuddy-ai Configure the WorkBuddy AI desktop app with CometAPI through the Custom provider dialog or models.json. Use the [WorkBuddy AI](https://www.workbuddy.ai/) desktop app with CometAPI through its OpenAI-compatible Custom provider. You can configure the connection in the app or with a `models.json` file. Official WorkBuddy AI references: * [Model Configuration](https://www.workbuddy.ai/docs/workbuddy/From-Beginner-to-Expert-Guide/Function-Description/Model) * [models.json Configuration Guide](https://www.workbuddy.ai/docs/cli/models) ## Prerequisites * [WorkBuddy AI](https://www.workbuddy.ai/) installed on your computer * A [CometAPI](https://www.cometapi.com) account with an active API key * A model ID from the [CometAPI model list](/overview/models) ## Choose a setup method > **[Configure in the app](#configure-the-app)** > > Use **Settings** → **Model** to add a Custom provider through the graphical interface. > **[Configure with models.json](#configure-models-json)** > > Store a reusable model definition in the user-level or project-level WorkBuddy AI configuration file. ## Configure the app **1. Open the model settings** In WorkBuddy AI, open **Settings** → **Model**, then select **Add Model**. **2. Select the Custom provider** In the **Provider** field, select **Custom**. This option accepts an OpenAI-compatible API connection. **3. Enter the CometAPI connection values** Enter the following values in the Add Model dialog: | Field | Value | | - | - | | Provider | `Custom` | | Endpoint | `https://api.cometapi.com/v1/chat/completions` | | API Key | Your CometAPI API key | | Model Name | The model ID from the [CometAPI model list](/overview/models) | The endpoint includes the complete `/chat/completions` path. Enable **Custom Protocol** so WorkBuddy sends the URL exactly as entered instead of adding another `/chat/completions` path. ![WorkBuddy AI Add Model dialog with the Custom provider and CometAPI connection fields](https://mintcdn.com/cometapi/yz6X9U_FscWpHj8q/images/integrations/workbuddy-ai-add-model.png?fit=max\&auto=format\&n=yz6X9U_FscWpHj8q\&q=85\&s=3dabe44ed2e5f275370cc55fb6960c38) The screenshot uses `gpt-6-astra` as an example model name. Choose a model ID that is available in your CometAPI account. **4. Set model capabilities** Enable **Tool Calling**, **Image Input**, or **Reasoning** only when the selected model supports that capability. Use **Reasoning Only** and **Allow Disabling Reasoning** when those controls match the model's reasoning behavior. **5. Test and save the model** In the Add Model dialog, click **Test connection**, then click **Save** after the connection check completes. ## Configure models.json WorkBuddy AI reads custom models from a user-level `~/.codebuddy/models.json` file or a project-level `/.codebuddy/models.json` file. Project-level configuration takes priority for matching model IDs. Create the configuration directory if it does not exist, then save the following JSON. The example uses an environment variable reference so that the API key does not appear in the file: ```json theme={null} { "models": [ { "id": "your-model-id", "name": "CometAPI model", "vendor": "CometAPI", "apiKey": "${COMETAPI_KEY}", "url": "https://api.cometapi.com/v1/chat/completions", "supportsToolCall": false, "supportsImages": false, "supportsReasoning": false } ], "availableModels": [ "your-model-id" ] } ``` Set `COMETAPI_KEY` in the environment that starts WorkBuddy AI. Replace `your-model-id` with a model ID from the [CometAPI model list](/overview/models). The `url` value must be the complete OpenAI Chat Completions path. Change a capability flag to `true` only when the selected model supports that capability. Set the file permissions to owner read/write on macOS or Linux: ```bash theme={null} chmod 600 "$HOME/.codebuddy/models.json" ``` If you use a project-level file, create it at `/.codebuddy/models.json` and keep the file out of version control when it contains local configuration. WorkBuddy AI reloads saved `models.json` changes and labels models added through the file as custom models. > [!NOTE] > > The `availableModels` array controls which model IDs appear in the model selector. If the array is empty or omitted, WorkBuddy AI displays all configured models. ## Verify the connection After either setup method, select the CometAPI model in the WorkBuddy AI model selector and send a short prompt, such as: ```text theme={null} Reply with one sentence: WorkBuddy AI is connected through CometAPI. ``` A response confirms that WorkBuddy AI can reach the configured CometAPI model. If the model does not appear, check that the model ID matches the CometAPI model list and that `availableModels` includes the same ID when you use that field. ## Troubleshooting > **The model does not appear in WorkBuddy AI** > > Confirm that the `id` value matches a CometAPI model ID. If `availableModels` is present, add the same ID to that array. For a project configuration, check `/.codebuddy/models.json` before the user-level file. > **The connection test fails** > > Check that the API key is active and that the endpoint is exactly `https://api.cometapi.com/v1/chat/completions`. For a `models.json` setup, confirm that `COMETAPI_KEY` is available in the environment that starts WorkBuddy AI. > **The request uses the wrong path** > > Use the complete `/chat/completions` path in the Endpoint field and the `url` field. In the app, enable **Custom Protocol** so WorkBuddy sends the complete URL without adding another path. > **The model sends unsupported features** > > Turn off capability flags that the selected model does not support. Tool calling, image input, and reasoning are independent settings. # 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) **1. Get your CometAPI API key** 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](https://mintcdn.com/cometapi/SZhlxZhCnMLn__BW/images/overview/810968_364191.png?fit=max\&auto=format\&n=SZhlxZhCnMLn__BW\&q=85\&s=aef81a83f29f8eb16655ed4060425f50) ![CometAPI API key details with base URL](https://mintcdn.com/cometapi/HhtmQffktazbxUvS/images/overview/810968_364193.png?fit=max\&auto=format\&n=HhtmQffktazbxUvS\&q=85\&s=d893f659267150d0faf45f99eb5dffc1) **2. Add CometAPI as a Zap step** In Zapier, create a new Zap. In the workflow editor, click **Add Step** and search for **CometAPI**. ![Zapier workflow editor with Add Step button](https://mintcdn.com/cometapi/E4FFvyMYmaOZoldp/images/integrations/810968_360288.png?fit=max\&auto=format\&n=E4FFvyMYmaOZoldp\&q=85\&s=e0f9acf9b0c6c296ba4590b3f94a8ca1) ![Zapier search results showing the CometAPI app](https://mintcdn.com/cometapi/E4FFvyMYmaOZoldp/images/integrations/810968_360289.png?fit=max\&auto=format\&n=E4FFvyMYmaOZoldp\&q=85\&s=f4a3fa5bf0e19ad96248a4b1dbfc2220) ![CometAPI action selection screen](https://mintcdn.com/cometapi/E4FFvyMYmaOZoldp/images/integrations/810968_360293.png?fit=max\&auto=format\&n=E4FFvyMYmaOZoldp\&q=85\&s=826cddfb18b75c459896d25e30ec69b4) **3. Configure the action and connect your account** * **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](https://mintcdn.com/cometapi/E4FFvyMYmaOZoldp/images/integrations/810968_360290.png?fit=max\&auto=format\&n=E4FFvyMYmaOZoldp\&q=85\&s=7512d3317a69a9387b59799e064f0060) **4. Select a model and test** Click **Continue**, choose the current model you want to use, then click **Continue** again and run **Test Step**. ![Zapier model selection step](https://mintcdn.com/cometapi/E4FFvyMYmaOZoldp/images/integrations/810968_360291.png?fit=max\&auto=format\&n=E4FFvyMYmaOZoldp\&q=85\&s=478bf8b48bd4e762807eeec15eb11785) ![Zapier test result showing a successful AI response](https://mintcdn.com/cometapi/E4FFvyMYmaOZoldp/images/integrations/810968_360292.png?fit=max\&auto=format\&n=E4FFvyMYmaOZoldp\&q=85\&s=18713a41c1a86a980c2bde6a6e072e48) 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). > [!TIP] > > 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) **1. Install the Zotero browser connector** In your browser's extensions panel, search for and install the **Zotero Connector**. ![Browser extension panel with Zotero search](https://mintcdn.com/cometapi/E4FFvyMYmaOZoldp/images/integrations/810968_360320.png?fit=max\&auto=format\&n=E4FFvyMYmaOZoldp\&q=85\&s=6b38564015afe74a9f4dc91a40613836) ![Zotero Connector extension installed in browser](https://mintcdn.com/cometapi/E4FFvyMYmaOZoldp/images/integrations/810968_360321.png?fit=max\&auto=format\&n=E4FFvyMYmaOZoldp\&q=85\&s=875d6f0f3a555f664bf2bea71a7964e8) **2. Get your CometAPI API key** 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](https://mintcdn.com/cometapi/SZhlxZhCnMLn__BW/images/overview/810968_364191.png?fit=max\&auto=format\&n=SZhlxZhCnMLn__BW\&q=85\&s=aef81a83f29f8eb16655ed4060425f50) ![CometAPI API key details with base URL](https://mintcdn.com/cometapi/HhtmQffktazbxUvS/images/overview/810968_364193.png?fit=max\&auto=format\&n=HhtmQffktazbxUvS\&q=85\&s=d893f659267150d0faf45f99eb5dffc1) **3. Install the Zotero GPT plugin** In Zotero, go to **Tools → Plugins → Install Plugin From File** and select the `zotero-gpt.xpi` file you downloaded. **4. Configure the API settings** 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](https://mintcdn.com/cometapi/E4FFvyMYmaOZoldp/images/integrations/810968_360325.png?fit=max\&auto=format\&n=E4FFvyMYmaOZoldp\&q=85\&s=8fc562a5ce6e0d559eba0298dfb58bce) **5. Test the integration** 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](https://mintcdn.com/cometapi/E4FFvyMYmaOZoldp/images/integrations/810968_360326.png?fit=max\&auto=format\&n=E4FFvyMYmaOZoldp\&q=85\&s=15978a05c5928698d718f954e4f2043f) If the call fails, verify your API key and address, or contact [CometAPI support](https://www.cometapi.com). # 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 **1. Get your CometAPI API key** 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](https://mintcdn.com/cometapi/SZhlxZhCnMLn__BW/images/overview/810968_364191.png?fit=max\&auto=format\&n=SZhlxZhCnMLn__BW\&q=85\&s=aef81a83f29f8eb16655ed4060425f50) ![CometAPI API key and base URL](https://mintcdn.com/cometapi/HhtmQffktazbxUvS/images/overview/810968_364193.png?fit=max\&auto=format\&n=HhtmQffktazbxUvS\&q=85\&s=d893f659267150d0faf45f99eb5dffc1) **2. Configure the base URL and API key** 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](https://mintcdn.com/cometapi/E4FFvyMYmaOZoldp/images/integrations/810968_360327.png?fit=max\&auto=format\&n=E4FFvyMYmaOZoldp\&q=85\&s=62fd70793e6356ac39eedc0f4694f3f2) ![Code example — ChatOpenAI initialization with CometAPI parameters](https://mintcdn.com/cometapi/mA1ovj6s0e3RM42l/images/integrations/810968_351552.png?fit=max\&auto=format\&n=mA1ovj6s0e3RM42l\&q=85\&s=b74bba832f1639b8135475f50fe307c6) **3. Test the connection** Run a simple chain (e.g., a prompt asking for the current date). A successful response confirms CometAPI is connected. > [!TIP] > > 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. # 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) **1. Install the LlamaIndex CometAPI integration** ```bash theme={null} pip install llama-index-llms-cometapi llama-index ``` **2. Set your API key** ```python theme={null} from llama_index.llms.cometapi import CometLLM import os os.environ["COMETAPI_KEY"] = "" api_key = os.getenv("COMETAPI_KEY") ``` > [!NOTE] > > Using environment variables is safer than hardcoding credentials in scripts. **3. Initialize the model and make completion calls** ```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) ``` **4. Enable streaming** 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="") ``` > **Tips and troubleshooting** > > * **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)