# Anthropic Introduction Source: https://docs.znapai.com/anthropic-intro *** ## Best suited for Anthropic Models ### Text Models * claude-sonnet-4-6 * claude-haiku-4-5 # Text Generation Source: https://docs.znapai.com/anthropic-text ## Request ```shellscript cURL theme={null} curl --request POST \ --url https://api.znapai.com/v1/messages \ --header 'x-api-key: $ZnapAI_API_KEY' \ --header "content-type: application/json" \ --data '{ "model": "claude-sonnet-4-6", "max_tokens": 200, "messages": [ { "role": "user", "content": "What is 2+2?" } ] }' ``` ```python Anthropic SDK (Python) theme={null} from anthropic import Anthropic client = Anthropic( api_key="$ZnapAI_API_KEY", base_url="https://api.znapai.com/" ) message = client.messages.create( max_tokens=200, messages=[ { "role": "user", "content": "What is 2+2?" } ], model="claude-sonnet-4-6", ) print(message) ``` ```javascript Anthropic SDK (JS) theme={null} import Anthropic from '@anthropic-ai/sdk'; const anthropic = new Anthropic({ apiKey: '$ZnapAI_API_KEY', baseURL: 'https://api.znapai.com/', }); const message = await anthropic.messages.create({ max_tokens: 200, messages: [{ role: 'user', content: 'What is 2+2?' }], model: 'claude-sonnet-4-6', }); console.log(message); ``` ## Response ```json theme={null} { "model": "claude-sonnet-4-6", "id": "msg_bdrk_013o7o9n5vpgAoN7PwkFBcAx", "type": "message", "role": "assistant", "content": [ { "type": "text", "text": "2 + 2 = **4**" } ], "stop_reason": "end_turn", "stop_sequence": null, "stop_details": null, "usage": { "input_tokens": 14, "cache_creation_input_tokens": 0, "cache_read_input_tokens": 0, "cache_creation": { "ephemeral_5m_input_tokens": 0, "ephemeral_1h_input_tokens": 0 }, "output_tokens": 14, "total_tokens": 28 } } ``` *** ## Vision (Image to Text) You can also pass images to the model for image-to-text generation. ### Request ```shellscript cURL theme={null} curl https://api.znapai.com/v1/messages \ --header 'x-api-key: $ZnapAI_API_KEY' \ --header "content-type: application/json" \ --data '{ "model": "claude-sonnet-4-6", "max_tokens": 1024, "messages": [ { "role": "user", "content": [ { "type": "image", "source": { "type": "base64", "media_type": "image/jpeg", "data": "'"$(base64 -w 0 image.jpg)"'" } }, { "type": "text", "text": "Describe this image in detail." } ] } ] }' ``` ```python Anthropic SDK (Python) theme={null} from anthropic import Anthropic import base64 client = Anthropic( api_key="$ZnapAI_API_KEY", base_url="https://api.znapai.com/" ) with open("path/to/image.jpg", "rb") as image_file: image_data = base64.b64encode(image_file.read()).decode("utf-8") message = client.messages.create( max_tokens=1024, messages=[ { "role": "user", "content": [ { "type": "image", "source": { "type": "base64", "media_type": "image/jpeg", "data": image_data } }, { "type": "text", "text": "Describe this image in detail." } ] } ], model="claude-sonnet-4-6", ) print(message) ``` ```javascript Anthropic SDK (JS) theme={null} import Anthropic from "@anthropic-ai/sdk"; import fs from "fs"; const anthropic = new Anthropic({ apiKey: "$ZnapAI_API_KEY", baseURL: "https://api.znapai.com/", }); const image_data = fs .readFileSync( "path/to/image.jpg", ) .toString("base64"); const message = await anthropic.messages.create({ max_tokens: 1024, messages: [ { role: "user", content: [ { type: "image", source: { type: "base64", media_type: "image/jpeg", data: image_data, }, }, { type: "text", text: "Describe this image in detail.", }, ], }, ], model: "claude-sonnet-4-6", }); console.log(message); ``` ### Response ```json theme={null} { "model": "claude-sonnet-4-6", "id": "msg_bdrk_01GTCduzzD8M7XfeXwx39Ltd", "type": "message", "role": "assistant", "content": [ { "type": "text", "text": "## Long Exposure Night Photography — Urban Highway\n\nThis is a **long exposure photograph** taken at night on a multi-lane urban road or highway, capturing the dynamic energy of city traffic.\n\n### Key Elements:\n\n**Light Trails**\n- Vivid **red, orange, and white streaks** streak across the road surface, created by vehicle headlights and taillights during the extended exposure\n- The trails suggest **heavy, fast-moving traffic** flowing in multiple lanes\n\n**Infrastructure**\n- A **large overhead bridge or flyover** dominates the upper right corner\n- Tall **street lamps** with warm sodium/LED lighting illuminate the scene from the left\n- **Street light poles** line the median and roadside\n\n**Vegetation**\n- **Trees illuminated in green and yellow** from artificial lighting are visible along the median/divider\n- The greenery suggests a well-maintained urban boulevard\n\n**Atmosphere**\n- The **dark night sky** contrasts dramatically with the colorful light trails\n- Blue and cyan light streaks in the distance add visual depth\n- The slight **camera movement** or zoom during exposure adds to the sense of **speed and motion**\n\n### Technical Notes:\n- Likely shot with a **slow shutter speed** (several seconds)\n- The image has a **cinematic, abstract quality** typical of intentional long-exposure urban photography" } ], "stop_reason": "end_turn", "stop_sequence": null, "stop_details": null, "usage": { "input_tokens": 1578, "cache_creation_input_tokens": 0, "cache_read_input_tokens": 0, "cache_creation": { "ephemeral_5m_input_tokens": 0, "ephemeral_1h_input_tokens": 0 }, "output_tokens": 301, "total_tokens": 1879 } } ``` *** ## Parameters The model that will complete your prompt. Input messages. The maximum number of tokens to generate before stopping. System prompt. Amount of randomness injected into the response. Use nucleus sampling. Only sample from the top K options for each subsequent token. Custom text sequences that will cause the model to stop generating. Whether to incrementally stream the response using server-sent events. An object describing metadata about the request. How the model should use the provided tools. Forces the model to use a specific tool. Configuration for extended thinking. The service tier for the request. *** ## Params to Avoid | Param | Reason | | -------------------- | ----------- | | `container` | Unsupported | | `context_management` | Unsupported | # Azure Image generation Source: https://docs.znapai.com/azure-image *** ## Request ```shellscript cURL theme={null} curl --location 'https://api.znapai.com/azure/openai/deployments/gpt-image-2/images/generations?api-version=2024-02-01' \ --header 'Authorization: Bearer $ZnapAI_API_KEY' \ --header 'Content-Type: application/json' \ --header 'spend-logs-metadata: {"user_id": "user-123", "project_id": "proj_abc", "env": "production"}' \ --data '{ "prompt": "A professional product photo of a white desk lamp on a neutral studio background, soft lighting, 50mm lens feel", "size": "1536x1024", "quality": "low", "n": 1, "output_format": "jpeg", "output_compression": 85, "background": "opaque", "moderation": "auto" }' ``` ## Response ```json theme={null} { "created": 1778262087, "background": "opaque", "data": [ { "b64_json": "/9j/4AAQSkZJRgABAQAAAQABAAD/60otSlACEQAAAAEAAEojanVtYgAAAB5qdW1kYzJwYQARABCAAACqADibcQNjMnBhAAAASf1qdW1iAAAAR2p1bWRjMm1hABEAEIAAAKoAOJtxA3VybjpjMnBhOjQzYjU5ZDJhLTMxMDEtNDcyOS1hMGU3LTkyMjBhODMyMmUxMQAAAAQWanVtYgAAAClqdW1kYzJhcwARABCAAACqgA0li0gADKgAErYCRQCQAZUbVlQAPF3gSAAlQCVJFAUkGJWgFAAkCQMGsAABIAJUKBIoBzqKSDCLQAAH/2Q==" } ], "output_format": "jpeg", "quality": "low", "size": "1536x1024", "usage": { "input_tokens": 29, "input_tokens_details": { "image_tokens": 0, "text_tokens": 29 }, "output_tokens": 158, "total_tokens": 187 } } ``` ## Image from base64 data Azure Image *** ## Parameters An optional header used for spend logging metadata, containing JSON properties like `user_id`, `project_id`, and `env`. A text description of the desired image(s). Maximum 32,000 characters. The number of images to generate. Must be between 1 and 10. Output image dimensions. Supports arbitrary `WIDTHxHEIGHT` where both edges are multiples of 16, aspect ratio between 1:3 and 3:1, max edge 3840. Standard values: `1024x1024`, `1536x1024`, `1024x1536`, `auto`. Supported values depend on the selected model. See the [OpenAI image generation guide](https://developers.openai.com/api/docs/guides/image-generation) for the latest model-specific ranges. Image quality level. Higher quality increases cost and latency. Allowed values: `low`, `medium`, `high`, `auto` Background behavior for the generated image. Allowed values: `opaque`, `auto` `transparent` is not supported on gpt-image-2. Compression level (0–100). Only applies when `output_format` is `jpeg`. Stream partial images as they are generated. Use with `--no-buffer` in curl. Number of partial images to emit during streaming. Value between `0` and `3`. Only used when `stream` is `true`. Content moderation strictness. Allowed values: `auto`, `low` *** ## Params to Avoid | Param | Reason | | --------------------------- | ---------------------------------------------------------------------------- | | `response_format: "url"` | Returns empty response from Azure | | `background: "transparent"` | Not supported on Azure gpt-image-2 | | `output_format: "webp"` | Not supported on Azure gpt-image-2 | | `style: "vivid"` | dall-e-3 only | | `spend-logs-metadata` | This metadata must be passed as an HTTP header, not in the JSON request body | The generation endpoint only returns `b64_json`. Requesting a URL response format is not supported and returns an empty response. # Azure Image editing Source: https://docs.znapai.com/azure-image-edit *** ## Request ```shellscript cURL theme={null} curl --location 'https://api.znapai.com/azure/openai/deployments/gpt-image-2/images/edits?api-version=2025-04-01-preview' \ --header 'Authorization: Bearer $ZnapAI_API_KEY' \ --header 'spend-logs-metadata: {"user_id": "user-123", "project_id": "proj_abc", "env": "production"}' \ --form 'prompt="Replace the background with a clean white studio surface, keep the product exactly as is"' \ --form 'image=@"/path/to/image.png"' \ --form 'size="1024x1024"' \ --form 'quality="low"' \ --form 'output_format="png"' ``` ## Input Input Image ## Response ```json theme={null} { "created": 1778264554, "background": "opaque", "data": [ { "b64_json": "iVBORw0KGgoAAAANSUhEUgAABAAAAAQACAIAAADwf7zUAABKMGNhQlgAAEowanVtYgAAAB5qdW1kYzJwYQARABCAAACqADibcQNjMnBhAAAASgpqdW1iAAAAR2p1bWRjMm1hABEAEIAAAKoAOJtxA3VybjpjMnBhOjcyYzUxM2NmLTIzMDEtNDE3Mi05NmY1LTQxZTRlYTlhY2YxNQAAAAQjanVtYgAAAClqdW1kYzJhcwARABCAAACqADibcQNjMnBhLmFzc2VydGlvbnMAAAACGGp1bWIAAABBanVtZGNib3IAEQAQgAAAqDYK4QD2QDSDyQwDaAzHORAQnA5grxTBLPZgO2ucIGbAMC24AAm2cyz2aBucIANgAYwIAENpdJABgAW1xmAPFMAsAGAGxsAJlnsrnCts0LIACwAWyezYAAzLMZyQBIANg8D4nLzGUCzDPZgA0gAIvLZMA2WICNDGADtrHBtgFAAGAuc7r9I/fGiQEGVOvlAAAAAElFTkSuQmCC" } ], "output_format": "png", "quality": "low", "size": "1024x1024", "usage": { "input_tokens": 39, "input_tokens_details": { "image_tokens": 16, "text_tokens": 23 }, "output_tokens": 196, "total_tokens": 235 } } ``` ## Image from base64 data Output Image *** ## Parameters An optional header used for spend logging metadata, containing JSON properties like `user_id`, `project_id`, and `env`. Text description of the desired edit. Reference image(s) to edit. Up to 16 images supported. Must be uploaded via multipart form data — image URLs are not supported. * `-F "image=@file.png"` or `-F "image[]=@file1.png" -F "image[]=@file2.png"` Alpha mask PNG. Transparent areas are regenerated; opaque areas are preserved. Must be uploaded via multipart — mask URLs are not supported. * `-F "mask=@mask.png"` Output image dimensions. Supports arbitrary `WIDTHxHEIGHT` where both edges are multiples of 16, aspect ratio between 1:3 and 3:1, max edge 3840. Standard values: `1024x1024`, `1536x1024`, `1024x1536`, `auto`. Supported values depend on the selected model. See the [OpenAI image generation guide](https://developers.openai.com/api/docs/guides/image-generation) for the latest model-specific ranges. Allowed values: `low`, `medium`, `high`, `auto` Number of edited images to return. Allowed values: `png`, `jpeg` `webp` is not supported on Azure gpt-image-2. Compression level (0–100). Only applies when `output_format` is `jpeg`. Allowed values: `auto`, `low` Stream partial edit results. Number of partial images during streaming (0–3). Only used when `stream` is `true`. *** ## Params to Avoid | Param | Reason | | --------------------------- | ---------------------------------------------------------------------------- | | `response_format: "url"` | Returns empty response from Azure | | `image_url` | Azure does not support image URLs — use file upload via multipart | | `input_fidelity: "low"` | gpt-image-2 rejects it on edits | | `background: "transparent"` | Not supported on Azure gpt-image-2 | | `output_format: "webp"` | Not supported on Azure gpt-image-2 | | `style: "vivid"` | dall-e-3 only | | `spend-logs-metadata` | This metadata must be passed as an HTTP header, not in the JSON request body | # Azure Introduction Source: https://docs.znapai.com/azure-introduction *** ## Best suited for Azure Models ### Image Models * gpt-image-2 * \+ more .. # Balance Source: https://docs.znapai.com/balance ## Request ```bash cURL theme={null} curl --location 'https://api.znapai.com/v1/balance' \ --header 'Authorization: Bearer $ZnapAI_API_KEY' ``` ## Response ```json theme={null} { "code": 200, "msg": "success", "data": 99.999578 } ``` # Cohere Introduction Source: https://docs.znapai.com/cohere-intro *** ## Cohere standard API format supports reranking models listed at [https://znapai.com/models](https://znapai.com/models) ### Rerank Models * cohere-rerank-v4.0-fast # Cohere Rerank Source: https://docs.znapai.com/cohere-rerank *** ## Request ```bash cURL theme={null} curl --location 'https://api.znapai.com/v1/rerank' \ --header 'Authorization: Bearer $ZnapAI_API_KEY' \ --header 'Content-Type: application/json' \ --data '{ "model": "cohere-rerank-v4.0-fast", "query": "What is the capital of France?", "documents": [ "Paris is the capital of France.", "Berlin is the capital of Germany.", "The Eiffel Tower is located in Paris." ] }' ``` ```python Cohere SDK (Python) theme={null} import cohere co = cohere.Client( api_key="$ZnapAI_API_KEY", base_url="https://api.znapai.com/v1" ) response = co.rerank( model="cohere-rerank-v4.0-fast", query="What is the capital of France?", documents=[ "Paris is the capital of France.", "Berlin is the capital of Germany.", "The Eiffel Tower is located in Paris." ] ) print(response) ``` ```javascript Cohere SDK (JS) theme={null} import { CohereClient } from "cohere-ai"; const cohere = new CohereClient({ token: "$ZnapAI_API_KEY", environment: "https://api.znapai.com/v1" }); const response = await cohere.rerank({ model: "cohere-rerank-v4.0-fast", query: "What is the capital of France?", documents: [ "Paris is the capital of France.", "Berlin is the capital of Germany.", "The Eiffel Tower is located in Paris." ] }); console.log(response); ``` ## Response ```json theme={null} { "id": "56df1b8a-22ab-49e8-b6fc-31c79838ca8f", "results": [ { "index": 0, "relevance_score": 0.8570099 }, { "index": 2, "relevance_score": 0.42403036 }, { "index": 1, "relevance_score": 0.36080432 } ], "meta": { "api_version": { "version": "2" }, "billed_units": { "search_units": 1 } } } ``` *** ## Parameters The name of the model to use for reranking. Supported model: `cohere-rerank-v4.0-fast`. The search query used to rank the documents. The list of documents to be reranked. Supports both simple string arrays and structured object arrays. The number of most relevant documents to return. Determines which fields in a structured object document are used for ranking. If omitted, the API automatically determines how to rank structured documents. If set to `true`, the ranked documents will be included in the response. Request priority (from 0 to 999). A lower value indicates a higher priority. The maximum number of tokens processed per document before truncation. *** ## Returns The response contains a unique ID, ranked results, and API usage metadata. A unique identifier for the rerank request. The ordered list of ranked documents, sorted by relevance score descending. The original index of the document in the request array. A score indicating how relevant the document is to the query. The returned document representation. Always normalized to a single `text` field. Metadata containing the API version and billed units. The API version information. The billed units for the request. The number of search units billed for this request. *** ## Behavior & Validation Notes ### 1. `rank_fields` is Optional The request succeeds even when `rank_fields` is omitted. The API automatically determines how to rank structured documents. ### 2. `rank_fields` Controls Ranking Providing specific fields in `rank_fields` (e.g., `["title"]`) restricts the model to only use those fields for calculation, overriding other fields (such as `text`). ### 3. Document Normalization in Response When `return_documents` is enabled, the API returns a **normalized** document containing **only** the `text` field. Original metadata fields (such as `title`, `author`, `year`, etc.) are stripped out of the response. ### 4. Independence of `rank_fields` and Response Inclusion Even if ranking is performed on fields like `title`, the returned document in `results.document` will still be normalized to the `text` field. ### 5. Billing based on Search Units Billing is calculated solely on **search units** (e.g., `billed_units.search_units`). There is no output token cost or separate pricing for input tokens. # OpenAI Audio generation Source: https://docs.znapai.com/essentials/audio *** ## Text to Speech Request ```shellscript cURL theme={null} curl --location 'https://api.znapai.com/v1/audio/speech' \ --header 'Authorization: Bearer $ZnapAI_API_KEY' \ --header 'Content-Type: application/json' \ --data '{ "model": "gpt-4o-mini-tts", "input": "Today is a wonderful day to build something people love!", "voice": "coral", "instructions": "Speak in a cheerful and positive tone." }' ``` ## Reponse Image *** ## Parameters Name of the model to use. Must be a suitable deployed audio model. Allowed values: * `tts-1` The text to generate audio for. Maximum length is 4096 characters. The voice to generate the audio in. Allowed values include `coral` and other standard OpenAI voices. Optional instructions to guide the style or tone of the generated audio. *** ## Params to Avoid | Param | Reason | | ----------------- | -------------------------------------------------------------- | | `response_format` | Format adjustments are not supported; audio is returned as MP3 | | `speed` | Speed adjustments are not supported | # OpenAI Image generation Source: https://docs.znapai.com/essentials/image *** ## Request ```shellscript cURL theme={null} curl --location 'https://api.znapai.com/images/generations' \ --header 'Content-Type: application/json' \ --header 'Authorization: Bearer $ZnapAI_API_KEY' \ --header 'spend-logs-metadata: {"user_id": "user-123", "project_id": "proj_abc", "env": "production"}' \ --data '{ "model": "gpt-image-2", "prompt": "Japanese negative film aesthetic, rooftop summer scene, soft natural sunlight, slight overexposure highlights, low contrast, muted faded colors, subtle grain subject standing or sitting on rooftop edge area, body relaxed, slight wind moving hair and clothes, looking toward camera with calm distant gaze, not posing open sky, empty space, minimal elements, imperfect composition, quiet isolated mood, nostalgic and reflective, “memory-like realism” --2:3", "n": 1, "size": "1024x1024", "quality": "low" }' ``` ```python OpenAI SDK (Python) theme={null} from openai import OpenAI client = OpenAI( api_key = "$ZnapAI_API_KEY", base_url = "https://api.znapai.com/" ) img = client.images.generate( model="gpt-image-2", prompt="Japanese negative film aesthetic, rooftop summer scene, soft natural sunlight, slight overexposure highlights, low contrast, muted faded colors, subtle grain subject standing or sitting on rooftop edge area, body relaxed, slight wind moving hair and clothes, looking toward camera with calm distant gaze, not posing open sky, empty space, minimal elements, imperfect composition, quiet isolated mood, nostalgic and reflective, “memory-like realism” --2:3", n=1, size="1024x1024", quality="low" ) with open("output.png", "wb") as f: f.write(image_bytes) ``` ```typescript OpenAI SDK (JS) theme={null} import OpenAI from "openai"; import { writeFile } from "fs/promises"; const client = new OpenAI({ apiKey: "$ZnapAI_API_KEY", baseURL: "https://api.znapai.com/" }); const img = await client.images.generate({ model: "gpt-image-2", prompt: "Japanese negative film aesthetic, rooftop summer scene, soft natural sunlight, slight overexposure highlights, low contrast, muted faded colors, subtle grain subject standing or sitting on rooftop edge area, body relaxed, slight wind moving hair and clothes, looking toward camera with calm distant gaze, not posing open sky, empty space, minimal elements, imperfect composition, quiet isolated mood, nostalgic and reflective, “memory-like realism” --2:3", n: 1, size: "1024x1024", quality: "low" }); const imageBuffer = Buffer.from(img.data[0].b64_json, "base64"); await writeFile("output.png", imageBuffer); ``` ## Response ```json theme={null} { "created": 1771066765, "background": null, "data": [ { "b64_json": "iVBORw0KGgoAAAA....", "revised_prompt": null, "url": null } ], "output_format": "png", "quality": "low", "size": "1024x1024", "usage": { "total_tokens": 4576, "input_tokens": 10, "input_tokens_details": { "image_tokens": 0, "text_tokens": 10 }, "output_tokens": 4566, "output_tokens_details": { "image_tokens": 4160, "text_tokens": 406 } } } ``` ## Image from base64 data Screenshot 2026 01 12 At 5 57 44 PM *** # Image generation with additional parameters for supported gemini models ## Request ```shellscript cURL theme={null} curl --location 'https://api.znapai.com/images/generations' \ --header 'Content-Type: application/json' \ --header 'Authorization: Bearer $ZnapAI_API_KEY' \ --header 'spend-logs-metadata: {"user_id": "user-123", "project_id": "proj_abc", "env": "production"}' \ --data '{ "model": "gemini-3-pro-image", "prompt": "A panda eating bamboo", "imageConfig": { "aspectRatio": "16:9", "imageSize": "1K" } }' ``` ## Response Gemini3 Image *** ## Parameters An optional header used for spend logging metadata, containing JSON properties like `user_id`, `project_id`, and `env`. Name of the model to use (for example: gpt-image-2). To see the complete list of supported image generation models, visit: [https://znapai.com/models/image\_generation](https://znapai.com/models/image_generation) A text description of the desired image(s). The maximum length is 32,000 characters for the GPT image models, 1,000 characters for `dall-e-2` and 4,000 characters for `dall-e-3`. The number of images to generate. Must be between 1 and 10. Output image dimensions. Supports arbitrary `WIDTHxHEIGHT` where both edges are multiples of 16, aspect ratio between 1:3 and 3:1, max edge 3840. Standard values: `1024x1024`, `1536x1024`, `1024x1536`, `auto`. Supported values depend on the selected model. See the [OpenAI image generation guide](https://developers.openai.com/api/docs/guides/image-generation) for the latest model-specific ranges. Image quality level. Higher quality increases cost and latency. Allowed values: `low`, `medium`, `high`, `auto` Background behavior for the generated image. Allowed values: `opaque`, `auto` `transparent` is not supported on gpt-image-2. Compression level (0–100). Only applies when `output_format` is `jpeg`. Stream partial images as they are generated. Use with `--no-buffer` in curl. Number of partial images to emit during streaming. Value between `0` and `3`. Only used when `stream` is `true`. Content moderation strictness. Allowed values: `auto`, `low` Optional configuration parameters for supported Gemini image models. The aspect ratio of the generated image (e.g. `16:9`, `1:1`, `4:3`). The resolution level of the image (e.g. `1K`, `2K`, `4K`). *** ## Params to Avoid | Param | Reason | | --------------------------- | ------------------------------------------------------------------------------ | | `response_format: "url"` | ZnapAI image endpoint only returns `b64_json` | | `background: "transparent"` | Not supported by OpenAI/Gemini image generation models | | `output_format: "webp"` | WebP output format is not supported | | `style` | Vivid or natural style configurations are DALL-E 3 exclusive and not supported | | `spend-logs-metadata` | This metadata must be passed as an HTTP header, not in the JSON request body | # OpenAI Image editing Source: https://docs.znapai.com/essentials/image-editing *** ## Request ```shellscript cURL theme={null} curl -X POST "https://api.znapai.com/v1/images/edits" \ -H "Authorization: Bearer $ZnapAI_API_KEY" \ -H 'spend-logs-metadata: {"user_id": "user-123", "project_id": "proj_abc", "env": "production"}' \ -F "model=gemini-3-pro-image" \ -F "image=@output.png" \ -F "prompt=An office group photo of these people, they are making funny faces." \ ``` ```python OpenAI (Python) theme={null} from openai import OpenAI # Initialize client with your proxy URL client = OpenAI( base_url="https://api.znapai.com/", api_key="$ZnapAI_API_KEY" ) # Edit an image response = client.images.edit( model="gemini-3-pro-image", image=open("output.png", "rb"), prompt="An office group photo of these people, they are making funny faces.", n=1, size="1024x1024" ) print(response) ``` ```typescript OpenAI (JS) theme={null} import fs from "fs"; import OpenAI, { toFile } from "openai"; const client = new OpenAI({ apiKey: "$ZnapAI_API_KEY", baseURL: "https://api.znapai.com/" }); const imageFiles = [ "output.png", ]; const images = await Promise.all( imageFiles.map(async (file) => await toFile(fs.createReadStream(file), null, { type: "image/png", }) ), ); const rsp = await client.images.edit({ model: "gemini-3-pro-image", image: images, prompt: "An office group photo of these people, they are making funny faces.", }); // Save the image to a file const image_base64 = rsp.data[0].b64_json; const image_bytes = Buffer.from(image_base64, "base64"); fs.writeFileSync("basket.png", image_bytes); ``` ## Input Output ## Response Result *** ## Parameters An optional header used for spend logging metadata, containing JSON properties like `user_id`, `project_id`, and `env`. Name of the model to use (for example: gemini-3.1-flash-image-preview). To see the complete list of supported image generation models, visit: [https://znapai.com/models/image\_generation](https://znapai.com/models/image_generation) Text description of the desired edit. Reference image(s) to edit. Must be uploaded via multipart form data — image URLs are not supported. Supported number of images: * `gemini-2.5-flash-image`: up to 3 images * `gemini-3.1-flash-image`: up to 14 images * `gemini-3-pro-image`: up to 14 images * GPT models: up to 16 images * `-F "image=@file.png"` or `-F "image[]=@file1.png" -F "image[]=@file2.png"` Alpha mask PNG. Transparent areas are regenerated; opaque areas are preserved. Must be uploaded via multipart — mask URLs are not supported. * `-F "mask=@mask.png"` Output image dimensions. Supports arbitrary `WIDTHxHEIGHT` where both edges are multiples of 16, aspect ratio between 1:3 and 3:1, max edge 3840. Standard values: `1024x1024`, `1536x1024`, `1024x1536`, `auto`. Supported values depend on the selected model. See the [OpenAI image generation guide](https://developers.openai.com/api/docs/guides/image-generation) for the latest model-specific ranges. Allowed values: `low`, `medium`, `high`, `auto` Number of edited images to return. Allowed values: `png`, `jpeg` `webp` is not supported on Azure gpt-image-2. Compression level (0–100). Only applies when `output_format` is `jpeg`. Allowed values: `auto`, `low` Stream partial edit results. Number of partial images during streaming (0–3). Only used when `stream` is `true`. *** ## Params to Avoid | Param | Reason | | --------------------------- | ---------------------------------------------------------------------------- | | `mask` | Some Gemini models do not support the mask parameter | | `response_format: "url"` | ZnapAI image endpoint only returns `b64_json` | | `background: "transparent"` | Not supported by image editing models | | `output_format: "webp"` | WebP output format is not supported | | `spend-logs-metadata` | This metadata must be passed as an HTTP header, not in the JSON request body | # OpenAI Video generation Source: https://docs.znapai.com/essentials/video *** ## Request ```bash cURL theme={null} theme={null} curl -X POST "https://api.znapai.com/v1/videos" \ -H "Authorization: Bearer $ZnapAI_API_KEY" \ -H "Content-Type: application/json" \ -d '{ "model": "sora-2", "prompt": "A cinematic drone shot flying through a futuristic cyberpunk city at night, volumetric lighting, realistic reflections, neon signs, rain-soaked streets", "size": "1280x720", "seconds": "4", "metadata": { "user_id": "test-user", "project": "video-api-testing" } }' ``` *** ## Parameters ### Required Parameters The video generation model identifier. Supported value: `"sora-2"`. A text description of the video you want to generate. ### Optional / Strict Parameters OpenAI's Sora validation is incredibly strict. Passing incorrect data types (like an integer instead of a string) or unsupported resolutions will result in a `400 Bad Request`. The duration of the video clip in seconds. **Must be a string.** Supported values: `"4"`, `"8"`, `"12"`. The output resolution formatted as `widthxheight`. Supported values for the standard `sora-2` model: `"720x1280"`, `"1280x720"` (720p only). `"1024x1792"` and `"1792x1024"` pass request validation but are rejected at generation time on the standard `sora-2` model (`"Resolution ... is not supported for model sora-2"`). These higher resolutions are exclusive to **Sora 2 Pro** — they are not usable on the standard model regardless of proxy configuration. An optional image reference (URL or base64 data) used to guide generation for Image-to-Video workflows. Optional metadata attached to the request for tracking, analytics, user identification, or application-specific context. Any valid JSON object is supported. ### Metadata Example ```json theme={null} theme={null} { "metadata": { "project": "video-api-testing", "user_id": "test-user-id-123", "environment": "staging" } } ``` *** ## Get Video Status The `POST /v1/videos` request returns a video job `id`. Use this `id` to poll the status of your generation job. ```bash cURL theme={null} theme={null} curl https://api.znapai.com/v1/videos/$VIDEO_ID \ -H "Authorization: Bearer $ZnapAI_API_KEY" ``` ### 200 Response Example ```json theme={null} theme={null} { "id": "id", "completed_at": 0, "created_at": 0, "error": { "code": "code", "message": "message" }, "expires_at": 0, "model": "string", "object": "video", "progress": 0, "prompt": "prompt", "remixed_from_video_id": "remixed_from_video_id", "seconds": "seconds", "size": "720x1280", "status": "queued" } ``` The `status` field indicates the current state of the video job. Possible values include `"queued"`, `"in_progress"`, and `"completed"`. Poll this endpoint until `status` changes to `"completed"` before downloading the video. *** ## Remix Video Once a video job's status is `"completed"`, you can remix it — apply a targeted change to the existing video (e.g. altering one element of the scene) instead of generating a new video from scratch. The original video's structure, motion, and framing are preserved. ```bash cURL theme={null} theme={null} curl -X POST "https://api.znapai.com/v1/videos/$VIDEO_ID/remix" \ -H "Authorization: Bearer $ZnapAI_API_KEY" \ -H "Content-Type: application/json" \ -d '{ "prompt": "Same scene, but shift the color palette to teal, sand, and rust with a warm backlight" }' ``` ### Path Parameters The unique identifier of a previously completed video job to remix. ### Required Parameters A text description of the targeted change to apply to the existing video. For best results, limit this to one clearly articulated adjustment — narrow, precise edits retain more fidelity to the source video and reduce the chance of visual defects. ### 200 Response Example ```json theme={null} theme={null} { "id": "id", "completed_at": null, "created_at": 0, "error": null, "expires_at": null, "model": "sora-2", "object": "video", "progress": 0, "prompt": "prompt", "remixed_from_video_id": "remixed_from_video_id", "seconds": "4", "size": "720x1280", "status": "queued" } ``` Remix returns a new video job `id` and sets `remixed_from_video_id` to the source video's `id`. Poll `GET /v1/videos/$VIDEO_ID` with the **new** `id` — the same way as [Get Video Status](#get-video-status) — until `status` changes to `"completed"` before downloading. *** ## Download Video Content Once the video job status is `"completed"`, download the generated video bytes or a derived preview asset using this endpoint. Streams the rendered video content for the specified video job. ### Path Parameters The unique identifier of the completed video job. ```bash cURL theme={null} theme={null} curl https://api.znapai.com/v1/videos/$VIDEO_ID/content \ -H "Authorization: Bearer $ZnapAI_API_KEY" ``` *** ## Common Errors to Avoid Due to an exception mapping quirk, if you violate any of OpenAI's parameter validations (e.g., passing `"duration"` instead of `"seconds"`), the proxy may wrap the OpenAI `400 Bad Request` inside a confusing `ContentPolicyViolationError`. * **Passing `duration` instead of `seconds`:** OpenAI expects `"seconds"`. It does not recognize `"duration"`. * **Passing `seconds` as an integer:** You must pass `"seconds": "4"`, not `"seconds": 4`. * **Passing an unsupported `size`:** Using standard sizes like `"1920x1080"` will fail. You must use the specific crop ratios allowed by OpenAI (e.g., `"1280x720"`). # Gemini Embedding Source: https://docs.znapai.com/gemini-embedding ## Request ```shellscript cURL theme={null} curl "https://api.znapai.com/gemini/v1beta/models/gemini-embedding-2:embedContent" \ -H "x-goog-api-key: $ZnapAI_API_KEY" \ -H "Content-Type: application/json" \ -d '{ "content": { "parts": [{"text": "What is the meaning of life?"}] } }' ``` ## Response ```json theme={null} { "embedding": { "values": [ 0.01234567, -0.09876543, 0.0054321 ] } } ``` *** ## Parameters The content to be embedded. Contains an ordered list of parts. An ordered list of parts that constitute the content. The text prompt or content to embed. Inline media data (e.g., images, video, audio) for multimodal embeddings. The MIME type of the media data (e.g., `image/png`, `audio/mpeg`, `video/mp4`, `application/pdf`). Base64 encoded media data. The maximum number of dimensions to include in the output embedding. Truncates the output vector. Recommended values: `768`, `1536`, `3072`. Only supported on `gemini-embedding-001` (legacy). Specifies the task type. Options: * `SEMANTIC_SIMILARITY`: Text similarity — recommendation, duplicate detection * `CLASSIFICATION`: Sentiment analysis, spam detection * `CLUSTERING`: Document organization, market research, anomaly detection * `RETRIEVAL_DOCUMENT`: Documents to be indexed/retrieved * `RETRIEVAL_QUERY`: Search queries (pair with `RETRIEVAL_DOCUMENT` for the docs) * `CODE_RETRIEVAL_QUERY`: Natural-language code search queries * `QUESTION_ANSWERING`: Questions in a QA system * `FACT_VERIFICATION`: Statements to verify against retrieved evidence *** ## Usage examples ### Alternative Route Prefix You can also use the `/v1beta/` route prefix instead of `/gemini/v1beta/`: ```shellscript cURL theme={null} curl "https://api.znapai.com/v1beta/models/gemini-embedding-2:embedContent" \ -H "x-goog-api-key: $ZnapAI_API_KEY" \ -H "Content-Type: application/json" \ -d '{"content": {"parts": [{"text": "What is the meaning of life?"}]}}' ``` > \[!NOTE] > You can also authenticate using the `?key=$ZnapAI_API_KEY` query parameter instead of the header if required by your integration. Both prefix routes support both auth styles. ### Multimodal embeddings (`gemini-embedding-2` only) All modalities map into the same embedding space. Example passing base64 image data: ```shellscript cURL theme={null} IMG_BASE64=$(base64 -w0 "/path/to/image.png") curl "https://api.znapai.com/gemini/v1beta/models/gemini-embedding-2:embedContent" \ -H "x-goog-api-key: $ZnapAI_API_KEY" \ -H "Content-Type: application/json" \ -d '{ "content": { "parts": [{ "inline_data": { "mime_type": "image/png", "data": "'"${IMG_BASE64}"'" } }] } }' ``` #### Supported modalities and limits | Modality | Specifications and limits | | --------------- | ------------------------------------------------------------------------------------------------------------------------------- | | Text | Up to 8,192 tokens | | Image | Max 6 images per request. PNG, JPEG | | Audio | Max 180s. MP3, WAV | | Video | Max 120s. MP4, MOV (H264, H265, AV1, VP9). Sampled at 1 fps (≤32s) or uniformly to 32 frames (longer). No audio track processed | | Documents (PDF) | Max 1 file per request, up to 6 pages | ### Batch embeddings (`batchEmbedContents`) Returns separate embeddings for multiple inputs in a single API call: ```shellscript cURL theme={null} curl "https://api.znapai.com/gemini/v1beta/models/gemini-embedding-2:batchEmbedContents" \ -H "x-goog-api-key: $ZnapAI_API_KEY" \ -H "Content-Type: application/json" \ -d '{ "requests": [ { "model": "models/gemini-embedding-2", "content": {"parts": [{"text": "An image of a dog"}]} }, { "model": "models/gemini-embedding-2", "content": {"parts": [{"text": "A cat on a mat"}]} } ] }' ``` ### Specify task type to improve performance #### Task types with Embeddings 2 (`gemini-embedding-2`) `gemini-embedding-2` does **not** accept a `task_type` field. Instead, prefix the task instruction directly into the text you embed. **Retrieval use cases (asymmetric format)** | Use case | Query structure | Document structure | | ------------------ | ---------------------------------------------- | ------------------------------------------------------------------- | | Search query | `task: search result \| query: {content}` | `title: {title} \| text: {content}` (use `title: none` if no title) | | Question answering | `task: question answering \| query: {content}` | `title: {title} \| text: {content}` | | Fact checking | `task: fact checking \| query: {content}` | `title: {title} \| text: {content}` | | Code retrieval | `task: code retrieval \| query: {content}` | `title: {title} \| text: {content}` | **Single-input use cases (symmetric format)** — use the same prefix for query and document. | Use case | Input structure | | ------------------- | ----------------------------------------------- | | Classification | `task: classification \| query: {content}` | | Clustering | `task: clustering \| query: {content}` | | Semantic similarity | `task: sentence similarity \| query: {content}` | Example structure query: ```shellscript cURL theme={null} curl "https://api.znapai.com/gemini/v1beta/models/gemini-embedding-2:embedContent" \ -H "x-goog-api-key: $ZnapAI_API_KEY" \ -H "Content-Type: application/json" \ -d '{"content": {"parts": [{"text": "task: search result | query: what is the meaning of life"}]}}' ``` #### Task types with Embeddings 001 (`gemini-embedding-001`) For `gemini-embedding-001`, pass the `taskType` in the request body: ```shellscript cURL theme={null} curl "https://api.znapai.com/gemini/v1beta/models/gemini-embedding-001:embedContent" \ -H "x-goog-api-key: $ZnapAI_API_KEY" \ -H "Content-Type: application/json" \ -d '{ "taskType": "SEMANTIC_SIMILARITY", "content": {"parts": [{"text": "What is the meaning of life?"}]} }' ``` ### Controlling embedding size `output_dimensionality` truncates the output vector. Both models default to 3072 dimensions. Recommended values: `768`, `1536`, `3072`. > \[!NOTE] > `gemini-embedding-2` auto-normalizes truncated dimensions (e.g. 768, 1536) so cosine similarity works correctly out of the box. `gemini-embedding-001` requires you to manually L2-normalize non-3072-dim vectors client-side. ```json theme={null} { "usage_object": { "total_tokens": 3, "prompt_tokens": 3, "completion_tokens": 0 }, "cost_breakdown": { "input_cost": 6e-7, "output_cost": 0, "original_cost": 6e-7, "total_cost": 3.6e-7 } } ``` *** ## Params to Avoid | Param | Reason | | ---------------------------------- | ---------------------------------------------------------------------------------------------------------------- | | `model` (top-level body field) | Model is specified in the URL path; a body `model` field is forwarded but ignored for routing | | `task_type` / `taskType` | Only valid for `gemini-embedding-001`; rejected by `gemini-embedding-2` — use prompt-prefix instructions instead | | `spend-logs-metadata` in JSON body | Must be passed as an HTTP header (`spend-logs-metadata`), not a body field | *** ## Model versions ### Gemini Embedding 2 | Property | Description | | --------------------- | ------------------------------------------------ | | Model code | `gemini-embedding-2` | | Input | Text, image, video, audio, PDF | | Output | Text embeddings | | Input token limit | 8,192 | | Output dimension size | Flexible: 128–3072. Recommended: 768, 1536, 3072 | ### Gemini Embedding 001 | Property | Description | | --------------------- | ------------------------------------------------ | | Model code | `gemini-embedding-001` | | Input | Text only | | Output | Text embeddings | | Input token limit | 2,048 | | Output dimension size | Flexible: 128–3072. Recommended: 768, 1536, 3072 | *** # Gemini Image editing Source: https://docs.znapai.com/gemini-image-editing # Image editing using Google GenAI SDK ```typescript cURL theme={null} curl --location 'https://api.znapai.com/gemini/v1beta/models/gemini-3.1-flash-image-preview:generateContent' \ --header 'x-goog-api-key: $ZnapAI_API_KEY' \ --header 'Content-Type: application/json' \ --header 'spend-logs-metadata: {"user_id": "user-123", "project_id": "proj_abc", "env": "production"}' \ --data '{ "contents": [{ "parts":[ {"text": "Edit this image and draw a yellow smiley in it"}, { "inline_data": { "mime_type":"image/jpeg", "data": "/9j/4AAQSkZJRgABAQAAAQABAAD/2wBDABALDA4MChAODQ4SERATGCgaGBYWGDEjJR0oOjM9PDkzODdASFxOQERXRTc4UG1RV19iZ2hnPk1xeXBkeFxlZ2P/2wBDARESEhgVGC8aGi9jQjhCY2NjY2NjY2NjY2NjY2NjY2NjY2NjY2NjY2NjY2NjY2NjY2NjY2NjY2NjY2NjY2NjY2P/wAARCABAAEADASIAAhEBAxEB/8QAHwAAAQUBAQEBAQEAAAAAAAAAAAECAwQFBgcICQoL/8QAtRAAAgEDAwIEAwUFBAQAAAF9AQIDAAQRBRIhMUEGE1FhByJxFDKBkaEII0KxwRVS0fAkM2JyggkKFhcYGRolJicoKSo0NTY3ODk6Q0RFRkdISUpTVFVWV1hZWmNkZWZnaGlqc3R1dnd4eXqDhIWGh4iJipKTlJWWl5iZmqKjpKWmp6ipqrKztLW2t7i5usLDxMXGx8jJytLT1NXW19jZ2uHi4+Tl5ufo6erx8vP09fb3+Pn6/8QAHwEAAwEBAQEBAQEBAQAAAAAAAAECAwQFBgcICQoL/8QAtREAAgECBAQDBAcFBAQAAQJ3AAECAxEEBSExBhJBUQdhcRMiMoEIFEKRobHBCSMzUvAVYnLRChYkNOEl8RcYGRomJygpKjU2Nzg5OkNERUZHSElKU1RVVldYWVpjZGVmZ2hpanN0dXZ3eHl6goOEhYaHiImKkpOUlZaXmJmaoqOkpaanqKmqsrO0tba3uLm6wsPExcbHyMnK0tPU1dbX2Nna4uPk5ebn6Onq8vP09fb3+Pn6/9oADAMBAAIRAxEAPwCxRRRXsHAFFFFABRRRQAUUUUAFFFFABRRRQAUUUUAFFFFABRRRQAUUUUAFFFFABRRRQAUUUUAFFFFABRRRQAUUUUAf/9k=" } } ] }] }' ``` ## Input Image ## Response Candidates 0 Content Parts 0 Inline Data Data (2) *** ## Parameters An optional header used for spend logging metadata, containing JSON properties like `user_id`, `project_id`, and `env`. The conversation history or input prompts as an array of content objects. The role of the creator of the content (e.g. `"user"` or `"model"`). An ordered list of parts that constitute a single message turn. The text instruction prompt for editing. The inline image data to be edited. The IANA media type of the image (e.g. `image/png`, `image/jpeg`). The base64-encoded image bytes. Instructions to the model that dictate how it should behave. An ordered list of parts that constitute the system instruction. The text of the system instruction. A list of tools the model may call. Supports `google_search` for search grounding. Tool configuration for any `Tool` specified in the request. Configuration for function calling behavior. Controls how the model uses the provided functions. One of: * `"AUTO"` — model decides whether to call a function or respond * `"ANY"` — model must call one of the provided functions * `"NONE"` — model must not call any functions Optional. Limits the model to only call functions from this list when `mode` is `"ANY"`. Configuration options for the generation. Controls the randomness of the output. The maximum cumulative probability of tokens to consider when sampling. The maximum number of tokens to consider when sampling. The maximum number of tokens to include in a candidate. Number of generated responses to return. Currently only `1` is supported for image generation. Allowed modalities of the output. Use `["TEXT", "IMAGE"]` to request image output. Settings for the output image. Aspect ratio of the generated image (e.g. `"16:9"`, `"1:1"`). Output image resolution level (e.g. `"1K"`, `"2K"`, `"4K"`). A list of sequences that will stop generation. A list of unique safety settings for blocking unsafe content. The category for this setting (e.g., `HARM_CATEGORY_HATE_SPEECH`). The threshold for blocking (e.g., `BLOCK_MEDIUM_AND_ABOVE`). *** ## Params to Avoid | Param | Reason | | ------------------------------------------------------- | ---------------------------------------------------------------------------------------------------------------------------------------------- | | `prompt`, `n`, `size`, `quality`, `stream` | OpenAI/Azure OpenAI parameters; sending these at the root level will fail schema validation. Use `contents` and `generationConfig` instead. | | `response_format`, `output_format` | Not supported by the Gemini API. Response format is determined by `responseModalities`. | | `background`, `output_compression`, `style` | OpenAI/Azure specific parameters; not supported by Gemini models. | | `generationConfig.responseMimeType: "application/json"` | Not supported when `responseModalities` includes `"IMAGE"`. | | `inlineData`, `mimeType` | CamelCase keys are used in the Vertex AI API, but the Gemini Developer API requires snake\_case (`inline_data`, `mime_type`) for inline media. | | `spend-logs-metadata` | This metadata must be passed as an HTTP header, not in the JSON request body | Ensure you do not mix OpenAI or Azure-specific parameters (such as `prompt`, `size`, `quality`, or `n`) with Gemini request structure. Gemini expects prompt text and the image input inside the nested `contents.parts` object using snake\_case keys. # Gemini Image generation Source: https://docs.znapai.com/gemini-image-generation ## Request ```shellscript cURL theme={null} curl --location 'https://api.znapai.com/gemini/v1beta/models/gemini-3.1-flash-image-preview:generateContent' \ --header 'x-goog-api-key: $ZnapAI_API_KEY' \ --header 'Content-Type: application/json' \ --header 'spend-logs-metadata: {"user_id": "user-123", "project_id": "proj_abc", "env": "production"}' \ --data '{ "contents": [{ "parts": [ {"text": "Create a picture of an F35 flying"} ] }] }' ``` ## Response Candidates 0 Content Parts 0 Inline Data Data ```json theme={null} { "candidates": [ { "content": { "parts": [ { "inlineData": { "mimeType": "image/jpeg", "data": "/9j/4AAQSkZJRgABAQEBLAEsAAD/+JpoOGMBqHGeRke60T7CXodaqWL92nEd0z8JH8Nvu24UMiCgWZSpq0jSaejI2QA3Y8NFdzPJtcHM4IqqhRR4WUV359PPHxmn/Vkn2yowWe3OXfCfXQhtSiN0hUk2KrjFmI5TyG18=" } ], "role": "model" }, "finishReason": "STOP", "index": 0 } ], "usageMetadata": { "promptTokenCount": 9, "candidatesTokenCount": 1586, "totalTokenCount": 1595, "promptTokensDetails": [ { "modality": "TEXT", "tokenCount": 9 } ], "candidatesTokensDetails": [ { "modality": "IMAGE", "tokenCount": 1120 } ] }, "modelVersion": "gemini-3.1-flash-image-preview", "responseId": "Y3Lead_eL62Ag8UP-tun8QU" } ``` *** # Image generation using Gemini model with additional parameters and tool calling ## Request ```shellscript cURL theme={null} curl --location 'https://api.znapai.com/v1beta/models/gemini-3.1-flash-image-preview:generateContent' \ --header 'x-goog-api-key: $ZnapAI_API_KEY' \ --header 'Content-Type: application/json' \ --header 'spend-logs-metadata: {"user_id": "user-123", "project_id": "proj_abc", "env": "production"}' \ --data '{ "contents": [{"parts": [{"text": "Visualize the current weather forecast for the next 5 days in San Francisco as a clean, modern weather chart. Add a visual on what I should wear each day"}]}], "tools": [{"google_search": {}}], "generationConfig": { "responseModalities": ["TEXT", "IMAGE"], "imageConfig": {"aspectRatio": "16:9", "imageSize": "2K"} } }' ``` ## Response Candidates 0 Content Parts 0 Inline Data Data (1) ```json theme={null} { "candidates": [ { "content": { "parts": [ { "inlineData": { "mimeType": "image/jpeg", "data": "/9j/4AAQSkZJRgABAQEBLAEsAAD/P2oO6jEwp8Kpx9u64pFvqRiLEPY0UjEW2XmNMgbG4E8u0G9BMV+IN8Bo1UFcJ5dIUw==" } ], "role": "model" }, "finishReason": "STOP", "index": 0, "groundingMetadata": { "searchEntryPoint": { "renderedContent": "\n
\n
\n \n \n \n \n \n \n \n \n \n \n \n \n \n
\n
\n
\n San Francisco current weather and clothing recommendation\n San Francisco 5-day weather forecast April 2026\n
\n
\n" }, "groundingChunks": [ { "web": { "uri": "https://vertexaisearch.cloud.google.com/grounding-api-redirect/AUZIYQH6YE7qjDm9XDBfg2DNU5jaK9nYfQ1W8k-vb-Xg0aqbkJn8LWkT5SaBDFlsreSeVrFVl4mjFlLjQuVZKrZZRpUPnSVBkabkENWLUc4srlaDzhr2-egP0K7y_sSQ67KWpbeplLE5WtFyVoL_tFRp5pUfUn4RBpgMllFp", "title": "sftourismtips.com" } }, { "web": { "uri": "https://vertexaisearch.cloud.google.com/grounding-api-redirect/AUZIYQHwiuxln0bc0hLj-q141I8u3JbRDx9Vo8kYoFJP5svPXlRainK9o7uM5tRlZrDWM1uu3EeMOp_SY_uv7jSZ3KyISJnfMU0F4lzNDMgkHX4LL2MP9k7RNcyoiqfpOh9JEIpCAGjndtVH3xuDCG0wpcJbX7ti8OHbPE4L9mmnbUnJx-V97dSt", "title": "accuweather.com" } }, { "web": { "uri": "https://www.google.com/search?q=weather+in+San Francisco, CA,+US", "title": "google.com" } } ], "webSearchQueries": [ "", "San Francisco 5-day weather forecast April 2026", "San Francisco current weather and clothing recommendation" ] } } ], "usageMetadata": { "promptTokenCount": 32, "candidatesTokenCount": 1796, "totalTokenCount": 1828, "promptTokensDetails": [ { "modality": "TEXT", "tokenCount": 32 } ], "candidatesTokensDetails": [ { "modality": "IMAGE", "tokenCount": 1120 } ] }, "modelVersion": "gemini-3.1-flash-image-preview", "responseId": "NHrNafm2FZaWg8UPo-TQ6Ak" } ``` *** ## Parameters An optional header used for spend logging metadata, containing JSON properties like `user_id`, `project_id`, and `env`. The conversation history or input prompts as an array of content objects. The role of the creator of the content (e.g. `"user"` or `"model"`). An ordered list of parts that constitute a single message turn. The text prompt or description for image generation. Instructions to the model that dictate how it should behave. An ordered list of parts that constitute the system instruction. The text of the system instruction. A list of tools the model may call. Supports `google_search` for search grounding. Tool configuration for any `Tool` specified in the request. Configuration for function calling behavior. Controls how the model uses the provided functions. One of: * `"AUTO"` — model decides whether to call a function or respond * `"ANY"` — model must call one of the provided functions * `"NONE"` — model must not call any functions Optional. Limits the model to only call functions from this list when `mode` is `"ANY"`. Configuration options for the generation. Controls the randomness of the output. The maximum cumulative probability of tokens to consider when sampling. The maximum number of tokens to consider when sampling. The maximum number of tokens to include in a candidate. Number of generated responses to return. Currently only `1` is supported for image generation. A list of sequences that will stop generation. Allowed modalities of the output. Use `["TEXT", "IMAGE"]` to request image output. Settings for generating images. Aspect ratio of the generated image (e.g. `16:9`, `1:1`). Output image resolution level (e.g. `1K`, `2K`, `4K`). A list of unique safety settings for blocking unsafe content. The category for this setting (e.g., `HARM_CATEGORY_HATE_SPEECH`). The threshold for blocking (e.g., `BLOCK_MEDIUM_AND_ABOVE`). *** ## Params to Avoid | Param | Reason | | ------------------------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------- | | `prompt`, `n`, `size`, `quality` | OpenAI/Azure OpenAI parameters; sending these at the root level will fail schema validation. Use `contents` and `generationConfig` instead. | | `response_format`, `output_format` | Not supported by the Gemini API. Response format is determined by `responseModalities`. | | `background`, `output_compression`, `style` | OpenAI/Azure specific parameters; not supported by Gemini models. | | `generationConfig.responseMimeType: "application/json"` | Not supported when `responseModalities` includes `"IMAGE"`. | | `spend-logs-metadata` | This metadata must be passed as an HTTP header, not in the JSON request body | Ensure you do not mix OpenAI or Azure-specific parameters (such as `prompt`, `size`, `quality`, or `n`) with Gemini's request structure. Gemini expects prompt text inside the nested `contents.parts` object. # Gemini Introduction Source: https://docs.znapai.com/gemini-intro *** ## Best suited for Google Models ### Text Models * gemini-2.5-pro * gemini-2.5-flash * gemini-2.5-flash-lite * gemini-3.1-pro-preview * gemini-3-flash-preview * \+ more .. ### Image Models * gemini-3.1-flash-image-preview * gemini-3-pro-image-preview * gemini-2.5-flash-image * \+ more .. ### Video Models * veo-3.1-lite-generate-preview * veo-3.1-fast-generate-preview * veo-3.1-generate-preview * * more .. # Gemini Text generation Source: https://docs.znapai.com/gemini-text-generation ## Request ```shellscript cURL theme={null} curl --location 'https://api.znapai.com/gemini/v1beta/models/gemini-3.1-flash-lite-preview:generateContent' \ --header 'x-goog-api-key: $ZnapAI_API_KEY' \ --header 'Content-Type: application/json' \ --header 'spend-logs-metadata: {"user_id": "user-123", "project_id": "proj_abc", "env": "production"}' \ --data '{ "contents": [{ "parts": [{"text": "Say hello"}] }] }' ``` ## Response ```json theme={null} { "candidates": [ { "content": { "parts": [ { "text": "Hello! How can I help you today?", "thoughtSignature": "EjQKMgG+Pvb77bf2HCbvhPqtGFBZnNbcz3s5bMch0bEGM796BQfxY+30wIBcyFIObyExxedG" } ], "role": "model" }, "finishReason": "STOP", "index": 0 } ], "usageMetadata": { "promptTokenCount": 2, "candidatesTokenCount": 9, "totalTokenCount": 11, "promptTokensDetails": [ { "modality": "TEXT", "tokenCount": 2 } ] }, "modelVersion": "gemini-3.1-flash-lite-preview", "responseId": "73HeadnqD7_Zg8UP5tae2Q0" } ``` *** ## Parameters An optional header used for spend logging metadata, containing JSON properties like `user_id`, `project_id`, and `env`. The conversation history or input prompts as an array of content objects. The role of the creator of the content (e.g. `"user"` or `"model"`). An ordered list of parts that constitute a single message turn. The text prompt or response content. System instructions that provide context, rules, or guidelines to the model. An ordered list of parts that constitute the system instruction. The text content of the system instruction. Configuration options for model generation and outputs. Controls the randomness of the output. The maximum cumulative probability of tokens to consider when sampling. The maximum number of tokens to consider when sampling. Number of generated responses to return. The maximum number of tokens to include in a candidate. A list of strings that tell the model to stop generating text. A list of `Tools` the model may use to generate the next response. Supported tools are function declarations and code execution. A list of function declarations the model can call. The name of the function to call. A description of what the function does. Describes the parameters for the function in JSON Schema format. The type of the parameters object. Usually `"object"`. A map of parameter names to their schema definitions. List of required parameter names. Enables the model to execute code as part of generation. Pass an empty object `{}` to enable. Tool configuration for any `Tool` specified in the request. Configuration for function calling behavior. Controls how the model uses the provided functions. One of: * `"AUTO"` — model decides whether to call a function or respond in text * `"ANY"` — model must call one of the provided functions * `"NONE"` — model must not call any functions Optional. When `mode` is `"ANY"`, limits the model to only call functions from this list. A list of unique safety settings for blocking unsafe content. The category for this setting (e.g. `HARM_CATEGORY_HATE_SPEECH`). Block threshold for this category (e.g. `BLOCK_MEDIUM_AND_ABOVE`). *** ## Params to Avoid | Param | Reason | | --------------------- | ---------------------------------------------------------------------------- | | `model` | Model is specified in the URL path, not in the request body | | `messages` | Native Gemini API uses `contents`, not `messages` | | `max_tokens` | Use `generationConfig.maxOutputTokens` instead | | `temperature` | Use `generationConfig.temperature` instead | | `top_p` | Use `generationConfig.topP` instead | | `top_k` | Use `generationConfig.topK` instead | | `stop` | Use `generationConfig.stopSequences` instead | | `presence_penalty` | Not natively supported by Gemini | | `frequency_penalty` | Not natively supported by Gemini | | `spend-logs-metadata` | This metadata must be passed as an HTTP header, not in the JSON request body | # Gemini Video generation Source: https://docs.znapai.com/gemini-video-generation ## 3-Step Video Generation Workflow ### Step 1: Initiate Video Generation Request a new video generation task by calling the `:predictLongRunning` RPC on the model. ```bash cURL theme={null} curl --location 'https://api.znapai.com/gemini/v1beta/models/veo-3.1-generate-preview:predictLongRunning' \ --header 'x-goog-api-key: $ZnapAI_API_KEY' \ --header 'Content-Type: application/json' \ --data '{ "instances": [ { "prompt": "A cat playing with a ball of yarn in a sunny garden" } ], "parameters": { "durationSeconds": 4, "resolution": "720p", "aspectRatio": "16:9" } }' ``` #### Response ```json theme={null} { "name": "models/veo-3.1-generate-preview/operations/{OPERATION_ID}" } ``` *** ### Step 2: Poll for Completion Using the operation ID returned from Step 1, poll the status endpoint until `"done": true` is returned. ```bash cURL theme={null} curl --location 'https://api.znapai.com/gemini/v1beta/models/veo-3.1-generate-preview/operations/{OPERATION_ID}' \ --header 'x-goog-api-key: $ZnapAI_API_KEY' ``` #### Response (Once Completed) ```json theme={null} { "name": "models/veo-3.1-generate-preview/operations/{OPERATION_ID}", "done": true, "response": { "@type": "type.googleapis.com/google.ai.generativelanguage.v1beta.PredictLongRunningResponse", "generateVideoResponse": { "generatedSamples": [ { "video": { "uri": "https://generativelanguage.googleapis.com/v1beta/files/{FILE_ID}:download?alt=media" } } ] } } } ``` *** ### Step 3: Download Video Substitute the Google API host (`https://generativelanguage.googleapis.com/v1beta`) with the proxy base URL (`https://api.znapai.com/gemini/v1beta`) to route the download request through ZnapAI. The query parameter `?alt=media` must be included at the end of the download request. Without it, the API will reject the request or return file metadata instead of the raw video bytes. ```bash cURL theme={null} curl --location 'https://api.znapai.com/gemini/v1beta/files/{FILE_ID}:download?alt=media' \ --header 'x-goog-api-key: $ZnapAI_API_KEY' \ --output generated_video.mp4 ``` *** ## Supported Generation Modes | Feature | Parameter(s) | Status | | :--------------------------- | :------------------------ | :------------------------------------------------------------- | | **Text → Video** | `prompt` | ✅ Supported | | **Image → Video** | `image` | ✅ Supported | | **First Frame & Last Frame** | `firstFrame`, `lastFrame` | ✅ Supported (only works with duration of 8 sec) | | **Video Extension** | `video` | ✅ Supported (not on lite; input must be a Veo-generated video) | | **Reference Images** | `referenceImages` | ✅ Supported (not on lite; requires 8 sec duration) | | **Video Duration** | `durationSeconds` | ✅ Supported | | **Aspect Ratio** | `aspectRatio` | ✅ Supported | | **Seed** | `seed` | ✅ Supported | | **Negative Prompt** | `negativePrompt` | ⚠️ Partial | ### Model Feature Support As tested through this proxy, `veo-3.1-generate-preview` and `veo-3.1-fast-generate-preview` behave identically for every feature below; `veo-3.1-lite-generate-preview` differs on reference images and negative prompt. | Feature | `veo-3.1-generate-preview` & `veo-3.1-fast-generate-preview` | `veo-3.1-lite-generate-preview` | | :----------------- | :----------------------------------------------------------- | :------------------------------------------ | | Text → Video | ✅ Supported | ✅ Supported | | Image → Video | ✅ Supported | ✅ Supported | | First & Last Frame | ✅ Supported (`durationSeconds: 8` required) | ✅ Supported (`durationSeconds: 8` required) | | Reference Images | ✅ Supported (`durationSeconds: 8` or omitted required) | ❌ Not supported (any duration) | | Video Extension | ✅ Supported (input must be a Veo-generated video) | ❌ Not supported | | Negative Prompt | ✅ Supported | ❌ Not supported | ### First & Last Frame Generation (Interpolation) You can generate a video transition between two images (a starting state and an ending state) by providing both a first frame and a last frame: * **First Frame:** Can be passed via `instances[0].firstFrame` or `instances[0].image`. * **Last Frame:** Must be passed via `instances[0].lastFrame`. The model will generate a smooth animation interpolating between the two frames based on the prompt. First-to-last frame interpolation requires **exactly 8 seconds** as the duration (`durationSeconds: 8`). Passing any value less than 8 is unsupported. Unlike `referenceImages`, first/last frame interpolation is supported across all three model variants: `veo-3.1-generate-preview`, `veo-3.1-lite-generate-preview`, and `veo-3.1-fast-generate-preview`. **Example Request:** ```bash cURL theme={null} curl --location 'https://api.znapai.com/gemini/v1beta/models/veo-3.1-generate-preview:predictLongRunning' \ --header 'x-goog-api-key: $ZnapAI_API_KEY' \ --header 'Content-Type: application/json' \ --data '{ "instances": [ { "prompt": "Smooth cinematic transition from a sunny orange-purple gradient scene with a yellow sun to a cool blue-green gradient scene with a red square target", "image": { "bytesBase64Encoded": "", "mimeType": "image/png" }, "lastFrame": { "bytesBase64Encoded": "", "mimeType": "image/png" } } ], "parameters": { "aspectRatio": "16:9", "durationSeconds": 8, "resolution": "720p" } }' ``` ### Reference Images (Subject Consistency) You can guide the appearance of a subject (e.g. a character or object) across the generated video by providing 1–3 reference images via `instances[0].referenceImages`, each with a `referenceType` of `"asset"`. `referenceImages` requires **exactly 8 seconds** as the duration (`durationSeconds: 8`), the same constraint as first/last frame interpolation. Passing any other value (e.g. `4`) causes the request to be rejected with a generic `"Your use case is currently not supported"` error — this looks like a model-support issue but is actually a duration mismatch. Omitting `durationSeconds` entirely also works. `referenceImages` is **not supported on `veo-3.1-lite-generate-preview`**, regardless of duration — it always returns a model-specific `400` error. It works on both `veo-3.1-generate-preview` and `veo-3.1-fast-generate-preview` once `durationSeconds` is set to `8` (or omitted). **Example Request:** ```bash cURL theme={null} curl --location 'https://api.znapai.com/gemini/v1beta/models/veo-3.1-generate-preview:predictLongRunning' \ --header 'x-goog-api-key: $ZnapAI_API_KEY' \ --header 'Content-Type: application/json' \ --data '{ "instances": [ { "prompt": "The blue robot character from the reference image walks across a futuristic neon city street at night, looking around curiously", "referenceImages": [ { "image": { "bytesBase64Encoded": "", "mimeType": "image/png" }, "referenceType": "asset" } ] } ], "parameters": { "aspectRatio": "16:9", "durationSeconds": 8, "resolution": "720p" } }' ``` ### Video Extension You can extend a previously generated Veo video by 7 seconds (repeatable up to 20 times) by passing it via `instances[0].video`. The input video **must be a video previously generated by Veo** (referenced via its file download URI), not an arbitrary uploaded video. Videos are retained for 2 days after generation, and referencing one for extension resets that 2-day timer. Pass the video as `"video": {"uri": ""}` — the URI returned from a prior `predictLongRunning` poll response (`response.generateVideoResponse.generatedSamples[0].video.uri`). Passing raw video bytes via `bytesBase64Encoded` (or `inlineData`) fails with `"Video URI not found in the request."` Video extension is **not supported on `veo-3.1-lite-generate-preview`**; it works on both `veo-3.1-generate-preview` and `veo-3.1-fast-generate-preview`. **Example Request:** ```bash cURL theme={null} curl --location 'https://api.znapai.com/gemini/v1beta/models/veo-3.1-generate-preview:predictLongRunning' \ --header 'x-goog-api-key: $ZnapAI_API_KEY' \ --header 'Content-Type: application/json' \ --data '{ "instances": [ { "prompt": "The camera continues panning across the cool blue-green gradient scene, the red square target pulses gently with light", "video": { "uri": "https://generativelanguage.googleapis.com/v1beta/files/:download?alt=media" } } ], "parameters": { "resolution": "720p" } }' ``` #### Chaining Extensions (Extend Again) To extend a video more than once, take the `uri` from the **most recent** extension's completed poll response — not the original input video — and pass that into the next extension request. The call shape is identical each time; only the `uri` and `prompt` change. Confirmed working: extending an already-extended video succeeds the same way as the first extension, with no different payload shape or extra fields required. Each successful call adds another \~7 seconds and returns a new `uri` to chain from for the next call, up to 20 times total. **Example Request (extending an already-extended video):** ```bash cURL theme={null} curl --location 'https://api.znapai.com/gemini/v1beta/models/veo-3.1-generate-preview:predictLongRunning' \ --header 'x-goog-api-key: $ZnapAI_API_KEY' \ --header 'Content-Type: application/json' \ --data '{ "instances": [ { "prompt": "The scene shifts further, the red square target now floats gently upward into a starry night sky", "video": { "uri": "https://generativelanguage.googleapis.com/v1beta/files/:download?alt=media" } } ], "parameters": { "resolution": "720p" } }' ``` ## Parameter Specifications ### Optional Parameters A text description of the video you want to generate. Input image for Image-to-Video generation. Can also be used as the starting (first) frame when paired with `lastFrame`. Input image to guide the ending (last) frame of the video, enabling smooth transition/interpolation between the first and last frames. A previously Veo-generated video to extend by 7 seconds. Must be passed as `{"uri": ""}`, not as raw bytes. Not supported on `veo-3.1-lite-generate-preview`. Supported on `veo-3.1-generate-preview` and `veo-3.1-fast-generate-preview`. See [Video Extension Validation](#video-extension-validation) below. A list of 1–3 images used to guide the appearance of a subject (e.g. a character or object) across the generated video. Each entry needs a `referenceType` of `"asset"`. Not supported on `veo-3.1-lite-generate-preview` (always rejected). Supported on `veo-3.1-generate-preview` and `veo-3.1-fast-generate-preview`, but **only when `durationSeconds` is `8`** (or omitted) — any other duration is rejected. See [Reference Images Model Support](#reference-images-model-support) below. The length of the generated video in seconds. Supported values: `4`, `6`, or `8`. If using first-to-last frame interpolation, the duration **must be set to exactly 8 seconds**; shorter durations are not supported. The aspect ratio of the output video. Supported values: `"16:9"`, `"9:16"`. The resolution of the output video. E.g., `"720p"`. A seed value to guide the randomness of generation. Description of elements you want to avoid in the video. This parameter is **not supported** by `veo-3.1-lite-generate-preview`. Passing it will trigger a `400 Bad Request` validation error. ## Validation & Error Behaviour ### Negative Prompt Validation on Lite Model Passing a `negativePrompt` parameter to the `veo-3.1-lite-generate-preview` model will result in a `400 Bad Request` error: ```json theme={null} { "error": { "message": "{\n \"error\": {\n \"code\": 400,\n \"message\": \"`negativePrompt` isn't supported by this model. Please remove it or refer to the Gemini API documentation for supported usage.\",\n \"status\": \"INVALID_ARGUMENT\"\n }\n}\n", "type": "None", "param": "None", "code": "400" } } ``` ### Reference Images Limit Providing more than 3 reference images will result in a validation error: ```json theme={null} { "error": { "message": "{\n \"error\": {\n \"code\": 400,\n \"message\": \"Number of reference images can not exceed 3.\",\n \"status\": \"INVALID_ARGUMENT\"\n }\n}\n", "type": "None", "param": "None", "code": "400" } } ``` * **Observed Behaviour:** 1–3 reference images are accepted; 4 or more reference images are rejected. ### Reference Images Model Support `referenceImages` (schema: `image.bytesBase64Encoded` + `referenceType: "asset"`) was tested against all three model variants. The key finding: it works on the full and fast models, but **only with `durationSeconds: 8`** — passing `4` (or `6`) triggers a generic error that looks like a model-support issue but is actually a duration mismatch. | Model | With `durationSeconds: 8` (or omitted) | With `durationSeconds: 4` | | :------------------------------ | :------------------------------------- | :-------------------------------- | | `veo-3.1-generate-preview` | ✅ Succeeds | ❌ Rejected (generic error) | | `veo-3.1-fast-generate-preview` | ✅ Succeeds | ❌ Rejected (generic error) | | `veo-3.1-lite-generate-preview` | ❌ Rejected (model-specific error) | ❌ Rejected (model-specific error) | **`veo-3.1-lite-generate-preview`** always rejects with a model-specific message, regardless of duration: ```json theme={null} { "error": { "message": "{\n \"error\": {\n \"code\": 400,\n \"message\": \"`referenceImages` isn't supported by this model. Please remove it or refer to the Gemini API documentation for supported usage.\",\n \"status\": \"INVALID_ARGUMENT\"\n }\n}\n", "type": "None", "param": "None", "code": "400" } } ``` **`veo-3.1-generate-preview`** and **`veo-3.1-fast-generate-preview`** reject with this generic message only when `durationSeconds` isn't `8`: ```json theme={null} { "error": { "message": "{\n \"error\": {\n \"code\": 400,\n \"message\": \"Your use case is currently not supported. Please refer to Gemini API documentation for current model offering.\",\n \"status\": \"INVALID_ARGUMENT\"\n }\n}\n", "type": "None", "param": "None", "code": "400" } } ``` * **Observed Behaviour:** With `durationSeconds: 8` set (or `parameters` omitted entirely), both the full and fast models return `200` and complete generation successfully. The lite model rejects unconditionally, confirming it's a genuine capability gap rather than a duration issue. ### `inlineData` Image Encoding Rejected Google's SDKs/REST examples wrap image bytes as `image: { inlineData: { mimeType, data } }`. This proxy does not accept that shape for any image field — use `bytesBase64Encoded` instead: ```json theme={null} { "error": { "message": "{\n \"error\": {\n \"code\": 400,\n \"message\": \"`inlineData` isn't supported by this model. Please remove it or refer to the Gemini API documentation for supported usage.\",\n \"status\": \"INVALID_ARGUMENT\"\n }\n}\n", "type": "None", "param": "None", "code": "400" } } ``` ### Video Extension Validation `instances[0].video` must reference a previously Veo-generated video by its file download URI — passing raw video bytes fails: ```json theme={null} { "error": { "message": "{\n \"error\": {\n \"code\": 400,\n \"message\": \"Video URI not found in the request.\",\n \"status\": \"INVALID_ARGUMENT\"\n }\n}\n", "type": "None", "param": "None", "code": "400" } } ``` `veo-3.1-lite-generate-preview` rejects video extension outright: ```json theme={null} { "error": { "message": "{\n \"error\": {\n \"code\": 400,\n \"message\": \"Video extension is not allowed for this model.\",\n \"status\": \"INVALID_ARGUMENT\"\n }\n}\n", "type": "None", "param": "None", "code": "400" } } ``` * **Observed Behaviour:** `{"video": {"uri": ""}}` succeeds and completes on both `veo-3.1-generate-preview` and `veo-3.1-fast-generate-preview`. `veo-3.1-lite-generate-preview` rejects the request regardless of payload shape. Chaining a second extension off an already-extended video's `uri` was also tested and completes successfully, with an identical request shape to the first extension. ### Validation Scenarios | Scenario | Result / Error | | :----------------------------------------------------------------- | :------------------------------------------------------------ | | **More than 3 reference images** | Rejected with correct validation error | | **`referenceImages` on lite model** | Rejected — unsupported on this model, any duration | | **`referenceImages` on full/fast model with `durationSeconds: 8`** | ✅ Succeeds | | **`referenceImages` on full/fast model with `durationSeconds: 4`** | Rejected — generic "use case not supported" error | | **`image` using `inlineData` encoding** | Rejected — proxy requires `bytesBase64Encoded` | | **`lastFrame` without `image`** | Unsupported request | | **`lastFrame` with `durationSeconds` under 8** | Unsupported request (requires exactly 8 seconds) | | **`video` with raw bytes (not a `uri`)** | Rejected — `"Video URI not found in the request."` | | **Video extension on lite model** | Rejected — `"Video extension is not allowed for this model."` | | **`fileData` parameter** | Explicitly rejected | *** ## Unsupported Fields ### fileData Passing `fileData` (such as `fileUri` or `mimeType` inside the `video` object) is explicitly unsupported: ```json theme={null} { "video": { "fileData": { "mimeType": "video/mp4", "fileUri": "..." } } } ``` **Response:** ``` `fileData` isn't supported by this model. ``` # Claude Code Source: https://docs.znapai.com/integrations/claude-code How to configure Claude Code to use ZnapAI. ## Overview This setup allows Claude Code to use models through Znap AI's Anthropic-compatible endpoint. ## Prerequisites Install Claude Code from [https://code.claude.com](https://code.claude.com) or using npm: ```bash theme={null} npm install -g @anthropic-ai/claude-code ``` Verify installation: ```bash theme={null} claude --version ``` ## Step 1: Configure Claude Code for Znap AI Open Terminal. Set the following environment variables for the current terminal session: ```powershell theme={null} $env:ANTHROPIC_BASE_URL="https://api.znapai.com/" $env:ANTHROPIC_AUTH_TOKEN="YOUR_ZNAP_API_KEY" $env:ANTHROPIC_MODEL="gemini-2.5-pro" ``` Replace `YOUR_ZNAP_API_KEY` with your actual API key. **Important:** These settings are temporary and only apply to the current PowerShell session. They will automatically be removed when the terminal is closed, allowing you to switch models or API keys without permanently modifying your system. ## Step 2: Launch Claude Code Start Claude Code: ```bash theme={null} claude ``` If configured correctly, Claude Code will launch using the specified model. You should see something similar to `gemini-2.5-pro · API Usage Billing` in the Claude Code header. Claude Code Header ## Step 3: Verify the Connection Run a simple prompt: ```text theme={null} What is 2 + 2? ``` If Claude Code responds successfully, your setup is complete. ## Changing Models To use a different model, update the environment variable: ```powershell theme={null} $env:ANTHROPIC_MODEL="YOUR_MODEL_NAME" ``` and restart Claude Code: ```bash theme={null} claude ``` Claude Code Terminal ### Viewing Available Models To see the list of available models configured through your gateway, run: ```text theme={null} /models ``` within Claude Code. Claude Code Models This will display the models currently available to your account, allowing you to select a different model and use its identifier in the `ANTHROPIC_MODEL` environment variable. Example: ```powershell theme={null} $env:ANTHROPIC_MODEL="gemini-2.5-pro" ``` After updating the model, restart Claude Code for the change to take effect. ## Notes * Claude Code is being configured through an Anthropic-compatible endpoint provided by Znap AI. * Different models may behave differently depending on the gateway's compatibility layer. * At the time of writing, `gemini-2.5-pro` has been tested and verified to work successfully with Claude Code. * If you encounter model-specific errors, try switching models and restarting Claude Code. ## Removing Temporary Configuration To clear the variables from the current session: ```powershell theme={null} Remove-Item Env:ANTHROPIC_BASE_URL Remove-Item Env:ANTHROPIC_AUTH_TOKEN Remove-Item Env:ANTHROPIC_MODEL ``` Alternatively, simply close the PowerShell window or terminal. ## Common Errors ### Error: Claude Code Requests Login If you get a login error, just re-run: ```powershell theme={null} $env:ANTHROPIC_BASE_URL="https://api.znapai.com/" $env:ANTHROPIC_AUTH_TOKEN="YOUR_ZNAP_API_KEY" $env:ANTHROPIC_MODEL="gemini-2.5-pro" ``` # Cline Source: https://docs.znapai.com/integrations/cline How to configure the Cline CLI and extension to use ZnapAI. ## Overview Cline is a powerful autonomous coding agent. By routing Cline through ZnapAI, you can power its capabilities with the most advanced language models available. ## Prerequisites * Ensure you have the **Cline** extension installed in your editor or via the CLI. Cline Extension ## Configuration Steps In the Cline settings panel: 1. Set the **API Provider** to `OpenAI Compatible`. 2. Choose the option **Bring my own API keys**. 3. Set the **Base URL** to `https://api.znapai.com/`. 4. Enter your **API Key**. 5. Enter the model name you wish to use (e.g., `claude-3-5-sonnet` or `gpt-4o`). Cline Options ## Base URL Use the standard ZnapAI endpoint: ```text theme={null} https://api.znapai.com/ ``` ## API Key Setup Your API Key can be generated from your ZnapAI dashboard. Keep it secure and paste it into the API Key field. ## Example Configuration ```bash CLI Example theme={null} export CLINE_API_BASE="https://api.znapai.com/" export CLINE_API_KEY="sk-znapai-..." cline start --model claude-3-5-sonnet ``` ## Troubleshooting * **Model Not Found**: Make sure you type the exact model ID as specified in the ZnapAI models page. * **Network Error**: Double-check that your Base URL does not include `/chat/completions` at the end, just `/v1`. # Codex Source: https://docs.znapai.com/integrations/codex How to configure Codex CLI to use ZnapAI. ## Overview Codex CLI is OpenAI's terminal-based coding agent. It can be configured to use Znap AI through an OpenAI-compatible endpoint. ## Step 1: Install Codex CLI Install globally using npm: ```bash theme={null} npm install -g @openai/codex ``` Verify installation: ```bash theme={null} codex --version ``` ## Step 2: Log Out of Existing OpenAI Sessions If you have previously logged into Codex using a ChatGPT account, clear the existing authentication first: ```bash theme={null} codex logout ``` This ensures Codex uses your custom configuration instead of stored OpenAI credentials. ## Step 3: Configure Codex Open the config file: ```text theme={null} C:\Users\\.codex\config.toml ``` Add the following: ```toml theme={null} openai_base_url = "https://api.znapai.com/v1" model = "gpt-5.3-codex" model_reasoning_effort = "high" ``` Save the file. ## Step 4: Start Codex Launch the CLI: ```bash theme={null} codex ``` Codex Terminal When prompted, select: ```text theme={null} Provide your own API key ``` Paste your Znap AI API key. ## Step 5: Verify Setup Run a simple prompt: ```text theme={null} What is 2 + 2? ``` If Codex responds successfully, the configuration is working. ## Changing Models Update the `model` field in your configuration file: ```text theme={null} C:\Users\\.codex\config.toml ``` Example: ```toml theme={null} model = "gpt-5.3-codex" ``` Restart Codex after making changes. ## Notes * Codex uses the OpenAI Responses API internally. * Znap AI successfully routes Codex requests through its OpenAI-compatible endpoint. * At the time of writing, GPT-based models have been verified to work reliably with Codex. * If you encounter errors such as: ```text theme={null} stream disconnected before completion ``` try switching to a GPT-based model and restart Codex. ## Troubleshooting ### Requests Still Going to OpenAI Run: ```bash theme={null} codex logout ``` Then restart Codex and re-enter your Znap AI API key. ### Invalid API Key Error Ensure you are using your Znap AI API key and not an OpenAI API key. ### Stream Disconnected Before Completion This usually indicates a compatibility issue between the selected model and Codex's Responses API requirements. Switch back to a GPT-based model: ```toml theme={null} model = "gpt-5.3-codex" ``` and restart Codex. ## Current Recommendation For Codex CLI, the most reliable configuration currently tested is: ```toml theme={null} openai_base_url = "https://api.znapai.com/v1" model = "gpt-5.3-codex" model_reasoning_effort = "high" ``` This configuration has been verified to work successfully with Znap AI. # Hermes Source: https://docs.znapai.com/integrations/hermes Setup Guide for Hermes Agent using ZnapAI Gateway # Hermes Agent Setup Guide ## Overview This document describes the complete installation and configuration process for Hermes Agent using a custom OpenAI-compatible API endpoint. *** # 1. Installation ### Windows (PowerShell) Open **PowerShell** and run: ```powershell theme={null} iex (irm https://raw.githubusercontent.com/NousResearch/hermes-agent/main/scripts/install.ps1) ``` ### macOS / Linux Install Hermes Agent using the official install script: ```bash theme={null} curl -fsSL https://raw.githubusercontent.com/NousResearch/hermes-agent/main/scripts/install.sh | bash ``` After installation, reload your shell and verify: ```bash theme={null} source ~/.bashrc hermes --version ``` The installer will: * Install Hermes Agent * Install required dependencies * Create configuration files * Add Hermes to PATH * Launch the setup wizard Setting up Hermes *** # 2. Setup Wizard ## Setup Type Prompt: ```text theme={null} How would you like to set up Hermes? 1. Quick Setup (Nous Portal) 2. Full setup ``` Selected: ```text theme={null} 2. Full setup ``` Reason: * Using a custom API gateway * Managing own API keys * Full control over provider configuration *** # 3. Model Provider Prompt: ```text theme={null} Select provider ``` Selected: ```text theme={null} 30. Custom endpoint (enter URL manually) ``` *** # 4. Endpoint Configuration ### Base URL Configured: ```text theme={null} https://api.znapai.com/v1 ``` ### API Compatibility Mode Prompt: ```text theme={null} 1. Auto-detect 2. Chat Completions 3. Responses / Codex 4. Anthropic Messages ``` Selected: ```text theme={null} 2. Chat Completions ``` Reason: * OpenAI-compatible endpoint * Uses `/chat/completions` *** # 5. Model Selection Hermes successfully queried the gateway and discovered available models. Example models returned: ```text theme={null} gpt-5.5 gpt-5 gpt-5.3-codex gpt-5.2-codex gpt-4o claude-opus-4.6 gemini-2.5-pro model-router ... ``` Selected model: ```text theme={null} ``` Recommended options: ### General Purpose ```text theme={null} gpt-5.5 ``` ### Coding ```text theme={null} gpt-5.3-codex ``` ### Dynamic Routing ```text theme={null} model-router ``` *** # 6. Context Length Prompt: ```text theme={null} Context length in tokens ``` Selected: ```text theme={null} Leave blank ``` Reason: * Allow Hermes to auto-detect model limits *** # 7. Provider Display Name Prompt: ```text theme={null} Display name ``` Configured: ```text theme={null} ZnapAI Gateway ``` (or any preferred name) Hermes Configuration *** # 8. Terminal Backend Prompt: ```text theme={null} Choose terminal backend ``` Selected: ```text theme={null} 1. Local ``` Reason: * Direct access to local repositories * Direct access to Node.js, Python, Git * Best experience for software development *** # 9. Messaging Platforms Prompt: ```text theme={null} Select messaging platforms ``` Selected: ```text theme={null} None ``` Action: ```text theme={null} Press Enter ``` Reason: * Focus on local coding workflow * Configure Telegram/Discord/etc. later if needed *** # 10. Tool Configuration Enabled: ```text theme={null} ✓ Web Search & Scraping ✓ Browser Automation ✓ Terminal & Processes ✓ File Operations ✓ Code Execution ✓ Vision ✓ Text-to-Speech ✓ Skills ✓ Task Planning ✓ Memory ✓ Session Search ✓ Clarifying Questions ✓ Task Delegation ✓ Cron Jobs ``` Disabled: ```text theme={null} ✗ Video Analysis ✗ Video Generation ✗ X Search ✗ Home Assistant ✗ Spotify ✗ Context Engine ``` *** # 11. Browser Automation Provider Prompt: ```text theme={null} Browser Automation Provider ``` Selected: ```text theme={null} 1. Local Browser ``` Reason: * Free * No API key required * Local Chromium execution *** # 12. Image Generation Provider Prompt: ```text theme={null} Image Generation Provider ``` Selected: ```text theme={null} Skip ``` Reason: * Not required for coding workflows * Can be configured later *** # 13. Text-to-Speech Provider Prompt: ```text theme={null} Text-to-Speech Provider ``` Selected: ```text theme={null} Microsoft Edge TTS ``` Reason: * Free * Local * No API key required *** # 14. Web Search Provider Prompt: ```text theme={null} Web Search Provider ``` Selected: ```text theme={null} DuckDuckGo (ddgs) ``` Reason: * Free * No API key required * Good enough for general research *** # 15. Installation Result Successful installation message: ```text theme={null} [OK] Installation Complete! ``` Files created: ```text theme={null} C:\Users\\AppData\Local\hermes\ ``` Important files: ```text theme={null} config.yaml .env cron/ sessions/ logs/ ``` *** # 16. Common Commands ## Start Hermes ```powershell theme={null} hermes ``` Hermes Terminal ## Re-run Setup ```powershell theme={null} hermes setup ``` ## Change Model ```powershell theme={null} hermes setup model ``` ## Configure Tools ```powershell theme={null} hermes setup tools ``` ## Configure Terminal Backend ```powershell theme={null} hermes setup terminal ``` ## Show Current Configuration ```powershell theme={null} hermes config ``` ## Edit Configuration ```powershell theme={null} hermes config edit ``` ## Run Diagnostics ```powershell theme={null} hermes doctor ``` ## Update Hermes ```powershell theme={null} hermes update ``` *** # 17. Configuration Location ## Config ```text theme={null} C:\Users\\AppData\Local\hermes\config.yaml ``` ## Environment Variables ```text theme={null} C:\Users\\AppData\Local\hermes\.env ``` *** # 18. Validation Steps After installation: ```powershell theme={null} hermes ``` Verify: ```text theme={null} What model are you using? ``` ```text theme={null} What tools are available? ``` ```text theme={null} List files in the current directory. ``` ```text theme={null} Create a todo list for understanding this repository. ``` If all commands succeed, the installation is complete and functional. # n8n Source: https://docs.znapai.com/integrations/n8n Setup Guide for n8n Local using ZnapAI Gateway # n8n Local Setup (Windows) with OpenAI-Compatible Gateway ## Prerequisites * Node.js installed * n8n installed globally ```powershell theme={null} npm install -g n8n ``` Verify installation: ```powershell theme={null} n8n --version ``` Start n8n: ```powershell theme={null} n8n start ``` n8n will be available at: ```text theme={null} http://localhost:5678 ``` *** # Initial Account Setup On first launch, n8n will prompt you to create an owner account. Fill in: ```text theme={null} Email First Name Last Name Password ``` Password requirements: * Minimum 8 characters * At least 1 uppercase letter * At least 1 number The "I want to receive security and product updates" checkbox is optional. After completing registration, you'll be redirected to the n8n dashboard. *** # Connecting n8n to an OpenAI-Compatible Gateway This method works with: * ZnapAI * Any OpenAI-compatible endpoint ## Step 1: Open Chat From the left sidebar: ```text theme={null} Chat ``` *** ## Step 2: Select a Model Click: ```text theme={null} Select a model ``` Choose: ```text theme={null} OpenAI ``` *** ## Step 3: Create Credentials When prompted, create a new credential. Enter: ```text theme={null} API Key: Base URL: https://api.znapai.com/v1 ``` n8n Configuration *** ## Step 4: Save Credential Click: ```text theme={null} Save ``` n8n will store the credential securely and make it available for future workflows and agents. *** ## Step 5: Test the Connection Send a message in the Chat interface. Example: ```text theme={null} Explain event-driven architecture in one paragraph. ``` If configured correctly: * n8n sends the request to your gateway * The gateway routes the request to the selected model * The response appears in the chat *** # Verification If using ZnapAI or any other Gateway Provider, monitor the gateway logs. You should see incoming requests from n8n whenever a chat message is sent. Example validation flow: ```text theme={null} n8n Chat ↓ OpenAI Credential ↓ Gateway (ZnapAI) ↓ Model Provider ↓ Response ``` If requests appear in gateway logs, the integration is working correctly. *** # Next Steps Once chat is working, you can build workflows and AI agents. Typical architecture: ```text theme={null} Webhook / Trigger ↓ AI Agent ↓ OpenAI-Compatible Gateway ↓ Tools ↓ Actions ``` Examples: * GitHub Issue Summarizer * Slack AI Assistant * CRM Lead Qualification Agent * Customer Support Automation * RAG Knowledge Assistant * Email Classification and Routing At this point, n8n is successfully configured to use your OpenAI-compatible gateway for both chat and workflow-based AI automation. # OpenClaw Source: https://docs.znapai.com/integrations/openclaw Setup Guide for OpenClaw Agent using ZnapAI Gateway # OpenClaw Setup on Windows with Custom Provider ## 1. Install OpenClaw You can install OpenClaw using the official installer or via npm. ### Option 1: Official Installer (Recommended) ### Windows (PowerShell) ```powershell theme={null} iwr -useb https://openclaw.ai/install.ps1 | iex ``` ### macOS / Linux ```bash theme={null} curl -fsSL https://openclaw.ai/install.sh | bash ``` This installs OpenClaw and performs the initial setup automatically. ### Option 2: Install via npm Requires Node.js to be installed. ```bash theme={null} npm install -g openclaw ``` ### Verify Installation ```bash theme={null} openclaw --version ``` You should see the installed OpenClaw version displayed. *** ## 2. Locate the Configuration File Open: ```text theme={null} C:\Users\\.openclaw\openclaw.json ``` or ```powershell theme={null} notepad $env:USERPROFILE\.openclaw\openclaw.json ``` Replace the entire contents of `openclaw.json` with: ```json theme={null} { "agents": { "defaults": { "workspace": "C:\\Users\\\\.openclaw\\workspace", "models": { "znapai/gpt-5.3-codex": { "alias": "GPT" } }, "model": { "primary": "znapai/gpt-5.3-codex" } } }, "models": { "mode": "merge", "providers": { "znapai": { "baseUrl": "https://api.znapai.com/v1", "apiKey": "${ZNAPAI_API_KEY}", "api": "openai-completions", "models": [ { "id": "gpt-5.3-codex", "name": "GPT-5.3 Codex", "contextWindow": 128000, "maxTokens": 32000 } ] } } }, "gateway": { "mode": "local", "auth": { "mode": "token", "token": "hello" }, "port": 18789, "bind": "loopback", "tailscale": { "mode": "off", "resetOnExit": false } } } ``` If you need to add additional models, ensure you add them to both the `agents.defaults.models` object and the `models.providers.znapai.models` array in the JSON file using the same format as `gpt-5.3-codex`. *** ## 3. Configure API Key Set the API key as an environment variable: ### For Current PowerShell Session ```powershell theme={null} $env:ZNAPAI_API_KEY="your-api-key" ``` Verify: ```powershell theme={null} echo $env:ZNAPAI_API_KEY ``` ### Permanent Configuration ```powershell theme={null} [Environment]::SetEnvironmentVariable( "ZNAPAI_API_KEY", "", "User" ) ``` Open a new PowerShell window and verify: ```powershell theme={null} echo $env:ZNAPAI_API_KEY ``` *** ## 4. Validate Configuration ```powershell theme={null} Get-Content $env:USERPROFILE\.openclaw\openclaw.json | ConvertFrom-Json ``` No output means the JSON is valid. *** ## 5. Start OpenClaw Gateway ```powershell theme={null} openclaw gateway ``` Expected output: ```text theme={null} [gateway] agent model: znapai/gpt-5.3-codex [gateway] ready ``` *** ## 6. Verify Gateway Health Open another terminal: ```powershell theme={null} openclaw gateway health ``` Expected: ```text theme={null} Gateway Health OK ``` Check status: ```powershell theme={null} openclaw gateway status ``` Expected: ```text theme={null} Listening: 127.0.0.1:18789 ``` *** ## 7. Launch OpenClaw ```powershell theme={null} openclaw ``` OpenClaw Terminal Initially, OpenClaw launches into **Crestodian**, the setup and troubleshooting assistant. Example: ```text theme={null} Hi, I'm Crestodian. - Start me when setup, config, Gateway, model choice, or agent routing feels off. - Using: znapai/gpt-5.3-codex for fuzzy local planning. ``` Crestodian is not the main conversational agent. To switch to the actual chat agent, type: ```text theme={null} talk to agent ``` Expected output: ```text theme={null} Opening your normal agent TUI. ``` After switching, you can chat normally with the configured model. *** ## Troubleshooting ### JSON Syntax Error Example: ```json theme={null} "apiKey": "${ZNAPAI_API_KEY}" "api": "openai-completions" ``` Missing comma. Correct: ```json theme={null} "apiKey": "${ZNAPAI_API_KEY}", "api": "openai-completions" ``` ### Unknown Model Error ```text theme={null} Unknown model: znapai/gpt-5.3-codex ``` Ensure: * Provider name is `znapai` * Default model is `znapai/gpt-5.3-codex` * Model exists under `models.providers.znapai.models[]` ### Gateway Start Blocked ```text theme={null} Gateway start blocked: existing config is missing gateway.mode ``` Ensure: ```json theme={null} "gateway": { "mode": "local" } ``` exists in the configuration. # OpenCode Source: https://docs.znapai.com/integrations/opencode How to configure OpenCode to use ZnapAI. ## Overview OpenCode is a collaborative web-based coding environment. Connecting OpenCode to ZnapAI unlocks premium code generation models directly within your web editor. ## Prerequisites * An active OpenCode account. ## Installation ### Step 1: Install OpenCode Download OpenCode from [https://opencode.ai/download](https://opencode.ai/download). Alternatively, the recommended installation method is via npm: ```bash theme={null} npm install -g opencode-ai ``` ### Step 2: Launch OpenCode Start OpenCode by running: ```bash theme={null} opencode ``` This opens the OpenCode terminal interface. OpenCode Terminal ### Step 3: Understanding Provider Setup Running the `/connect` command only configures built-in providers. To use ZnapAI, you must use the Custom AI Provider settings. ## Configuration Steps 1. Open your OpenCode settings. 2. Navigate to the **Custom AI Provider** section. 3. Input the **Base URL**: `https://api.znapai.com/` 4. Provide your **API Key** to authenticate. OpenCode Popular Providers ## Base URL ```text theme={null} https://api.znapai.com/ ``` ## API Key Setup Copy your key from the ZnapAI console and paste it into the secure API Key input in OpenCode. ## Example Configuration By default, the OpenCode configuration file contains: ```json config.json theme={null} { "$schema": "https://opencode.ai/config.json" } ``` Replace it with the following configuration: ```json config.json theme={null} { "$schema": "https://opencode.ai/config.json", "provider": { "znap": { "npm": "@ai-sdk/openai-compatible", "options": { "baseURL": "https://api.znapai.com/", "apiKey": "YOUR_API_KEY" } } } } ``` Save the file once you have replaced `YOUR_API_KEY` with your actual ZnapAI credentials. ## Troubleshooting * If OpenCode fails to generate responses, check your balance on the ZnapAI dashboard. * Verify your network allows outbound requests to `api.znapai.com`. ## Notes * OpenCode's chat features are fully supported via the standard completions API format. # Integrations Overview Source: https://docs.znapai.com/integrations/overview Connect your favorite AI coding assistants to the ZnapAI gateway using your API Key and Base URL. ## Quick Setup To configure any OpenAI-compatible tool to work with ZnapAI, you will generally need two pieces of information: `https://api.znapai.com/` Your ZnapAI API Key *** ## Supported Tools Select your preferred tool below to view detailed setup instructions. Setup for Roo Code IDE extension Setup for the Cline CLI and extension Setup for OpenCode platform Setup for Claude Code extension Setup for Codex terminal Setup for Hermes Agent Setup for OpenClaw Agent Setup for n8n Local Setup for Vercel AI SDK integration If you don't see your tool listed here, look for an **"OpenAI Compatible"** or **"Custom Endpoint"** setting in your tool's configuration and use our Base URL and API Key. # Roo Code Source: https://docs.znapai.com/integrations/roo-code How to configure the Roo Code extension to use ZnapAI. ## Overview Roo Code is an advanced AI coding assistant that integrates directly into your IDE. By connecting Roo Code to ZnapAI, you gain access to our extensive model selection seamlessly. ## Prerequisites * Ensure you have the **Roo Code** extension installed in your IDE. Roo Code Extension ## Configuration Steps Follow these steps to configure the extension: 1. Open Roo Code settings. 2. Select **OpenAI Compatible** as the API Provider. 3. Enter the **Base URL**: `https://api.znapai.com/` 4. Enter your **ZnapAI API Key**. 5. Select your desired model. Roo Code Settings Configuration ## Base URL Use the following Base URL for OpenAI compatible providers: ```text theme={null} https://api.znapai.com/ ``` ## API Key Setup You can find your API key in the ZnapAI dashboard under the API Keys section. Paste it into the API Key field in Roo Code. ## Example Configuration ```json settings.json theme={null} { "rooCode.apiProvider": "OpenAI Compatible", "rooCode.baseUrl": "https://api.znapai.com/", "rooCode.apiKey": "sk-znapai-..." } ``` Once configured, you can start using the Roo Code chat window to interact with ZnapAI models. Roo Code Chat Window ## Troubleshooting * **Connection Error**: Ensure there you enter correct Base URL. * **Authentication Failed**: Verify that your API Key is active in the ZnapAI dashboard. ## Notes * Roo Code supports all models listed under the ZnapAI OpenAI-compatible endpoint. # Vercel AI SDK Source: https://docs.znapai.com/integrations/vercel-ai-sdk Learn how to integrate the Vercel AI SDK with OpenAI-compatible language models. The **Vercel AI SDK** provides a simple and unified API for interacting with OpenAI-compatible language models. This guide explains how to integrate the SDK with OpenAI or any OpenAI-compatible API endpoint for text generation, streaming, image generation, and multimodal (vision) capabilities. *** ## Prerequisites Before you begin, ensure you have: * Node.js 18+ * An OpenAI-compatible API endpoint * An API key * npm or another package manager *** ## Installation Install the required packages: ```bash theme={null} npm install ai @ai-sdk/openai dotenv ``` ### Package Overview | Package | Description | | ---------------- | -------------------------------------------------------------------------- | | `ai` | Core Vercel AI SDK containing text generation, streaming, and image APIs. | | `@ai-sdk/openai` | OpenAI provider that supports both OpenAI and OpenAI-compatible endpoints. | | `dotenv` | Loads API keys and configuration from environment variables. | *** ## Environment Variables Create a `.env` file: ```env theme={null} API_KEY=your_api_key BASE_URL=https://your-openai-compatible-endpoint/v1 MODEL_NAME=gpt-4o-mini IMAGE_MODEL_NAME=gpt-image-2 ``` `BASE_URL` is optional when using the official OpenAI API. Specify it only when connecting to an OpenAI-compatible provider or proxy. *** ## Client Configuration Create a reusable client configuration. ```typescript theme={null} import { createOpenAI } from '@ai-sdk/openai'; import * as dotenv from 'dotenv'; dotenv.config(); const apiKey = process.env.API_KEY; const baseURL = process.env.BASE_URL; export const MODEL = process.env.MODEL_NAME; export const IMAGE_MODEL = process.env.IMAGE_MODEL_NAME; export const openai = createOpenAI({ apiKey, baseURL, }); ``` *** *** ## Next Steps To explore individual capabilities with code examples, check the following sections in the sidebar: * [Text Generation](/integrations/vercel-ai-sdk-text) * [Image Generation](/integrations/vercel-ai-sdk-image) * [Image to Text (Vision)](/integrations/vercel-ai-sdk-vision) *** ## Best Practices * Store API keys in environment variables. * Reuse a single OpenAI client instance throughout your application. * Use streaming for chat interfaces to improve user experience. * Validate generation parameters before making requests. * Handle API errors gracefully with retry or fallback logic. * Use system prompts to define consistent assistant behavior. * Keep prompts concise and specific for better model responses. *** ## Supported Features | Feature | Supported | | -------------------------- | --------- | | Text Generation | ✅ | | Streaming Responses | ✅ | | System Prompts | ✅ | | Temperature | ✅ | | Top P | ✅ | | Top K | ✅ | | Max Tokens | ✅ | | Frequency Penalty | ✅ | | Presence Penalty | ✅ | | Seed | ✅ | | Stop Sequences | ✅ | | Image Generation | ✅ | | Vision (Image Input) | ✅ | | OpenAI-Compatible Base URL | ✅ | *** ## Next Steps You are now ready to build applications using the Vercel AI SDK with any OpenAI-compatible endpoint. Explore additional SDK capabilities such as structured outputs, tool calling, agents, and chat history management as your application grows. # Image Generation Source: https://docs.znapai.com/integrations/vercel-ai-sdk-image Learn how to generate images using the Vercel AI SDK. The Vercel AI SDK supports generating images from text prompts using compatible models. *** ## Image Generation Generate images using `experimental_generateImage()`. ```typescript theme={null} import { experimental_generateImage as generateImage, } from 'ai'; import { openai, IMAGE_MODEL, } from './client'; async function makeImage() { const result = await generateImage({ model: openai.image(IMAGE_MODEL), prompt: 'A sunset over the mountains, digital art', n: 1, size: '1024x1024', }); if (result.image?.base64) { console.log('Received Base64 image.'); } else if (result.images?.[0]?.url) { console.log(result.images[0].url); } } ``` *** ## Parameters When using `experimental_generateImage`, the following parameters are supported: The image model instance to use for generation. The text description of the image to generate. The number of images to generate. The size of the generated image (e.g. `"1024x1024"`). # Text Generation Source: https://docs.znapai.com/integrations/vercel-ai-sdk-text Learn how to use the Vercel AI SDK for text generation, streaming responses, and handling parameters or errors. The Vercel AI SDK provides powerful functions for text generation and streaming. Below are details and examples for implementing these functions. *** ## Text Generation Use `generateText()` for standard, non-streaming responses. ```typescript theme={null} import { generateText } from 'ai'; import { openai, MODEL } from './client'; async function generateGreeting() { const response = await generateText({ model: openai(MODEL), prompt: 'Explain quantum computing in one sentence.', }); console.log(response.text); } ``` *** ## Streaming Responses Use `streamText()` to stream tokens as they are generated. ```typescript theme={null} import { streamText } from 'ai'; import { openai, MODEL } from './client'; async function streamResponse() { const result = await streamText({ model: openai(MODEL), prompt: 'Write a poem about a software engineer.', }); for await (const chunk of result.textStream) { process.stdout.write(chunk); } } ``` Streaming improves perceived latency and is recommended for chat interfaces. *** ## System Prompts & Parameters You can customize model behavior using a system prompt and generation parameters. ### Supported Parameters The model instance to use for generation. The text prompt to generate a response for. Either `prompt` or `messages` is required. System instructions to guide the model's behavior. Controls randomness. Lower values produce more deterministic responses. Maximum number of tokens generated. Nucleus sampling probability. Limits sampling to the top K probable tokens. Encourages introducing new topics. Reduces repeated words or phrases. Produces deterministic outputs when supported. Stops generation when one of the specified sequences is encountered. ## Error Handling Wrap SDK calls in a `try...catch` block to handle API errors, validation failures, and authentication issues. ```typescript theme={null} import { generateText } from 'ai'; import { openai, MODEL } from './client'; async function safeGenerate() { try { const response = await generateText({ model: openai(MODEL), prompt: 'Hello!', temperature: -1, }); console.log(response.text); } catch (error: any) { console.error('Error:', error.name); console.error(error.message); } } ``` Common errors include: * Invalid API key * Incorrect endpoint URL * Unsupported model * Invalid request parameters * Rate limits # Image to Text Source: https://docs.znapai.com/integrations/vercel-ai-sdk-vision Learn how to use multimodal input (Vision) with the Vercel AI SDK. Multimodal language models can accept both text prompts and images as input. *** ## Vision (Image-to-Text) Pass both text and image content to a multimodal model. ```typescript theme={null} import { generateText } from 'ai'; import { openai, MODEL } from './client'; async function analyzeImage() { const base64Image = 'iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAYAAAAfFcSJAAAADUlEQVR42mP8z8BQDwAEhQGAhKmMIQAAAABJRU5ErkJggg=='; const response = await generateText({ model: openai(MODEL), messages: [ { role: 'user', content: [ { type: 'text', text: 'Describe this image.', }, { type: 'image', image: base64Image, mimeType: 'image/png', }, ], }, ], }); console.log(response.text); } ``` *** ## Parameters When using vision models with `generateText`, the following parameters are supported: The model instance to use for generation. Array of message objects representing the conversation history. For vision, pass `type: 'image'` along with the image data (URL or Base64) and `mimeType`. Controls randomness (0.0 to 2.0). The maximum number of tokens to generate. Nucleus sampling probability. Limits sampling to the top K probable tokens. Encourages the model to talk about new topics. Prevents the model from repeating words. Attempts deterministic generation. Custom sequences that stop the model from generating further text. # Introduction Source: https://docs.znapai.com/introduction One API key for OpenAI, Gemini, Vertex AI, Azure, and more ## Explore by provider Chat completions, responses, image generation, image editing, audio, and video through a fully OpenAI-compatible endpoint. Text generation via the Anthropic Messages API. Native text generation, image generation, and image editing via the Google GenAI API format. Enterprise-grade access to Google's latest models via the Vertex AI API format with full camelCase compatibility. Image generation and image editing through the Azure OpenAI API format with your existing Azure workflows. Document reranking and semantic search acceleration via the Cohere Rerank API format. Integrate ZnapAI using Vercel's unified AI SDK for text generation, streaming, image generation, and vision. ## Start in minutes ZnapAI is compatible with the OpenAI SDK — change only `base_url` and `api_key`: ```bash cURL theme={null} curl --location 'https://api.znapai.com/v1/chat/completions' \ --header 'Content-Type: application/json' \ --header 'Authorization: Bearer $ZnapAI_API_KEY' \ --data '{ "model": "gpt-4o-mini", "messages": [ { "role": "user", "content": "Hello!" } ] }' ``` ```python OpenAI SDK (Python) theme={null} import os import openai client = openai.OpenAI( api_key=os.environ["ZnapAI_API_KEY"], base_url="https://api.znapai.com/v1" ) response = client.chat.completions.create( model="gpt-4o-mini", messages=[{"role": "user", "content": "Hello!"}] ) print(response.choices[0].message.content) ``` ```typescript OpenAI SDK (JS) theme={null} import OpenAI from "openai"; const client = new OpenAI({ apiKey: process.env.ZnapAI_API_KEY, baseURL: "https://api.znapai.com/v1", }); const response = await client.chat.completions.create({ model: "gpt-4o-mini", messages: [{ role: "user", content: "Hello!" }], }); console.log(response.choices[0].message.content); ``` Already using the OpenAI SDK? Only `base_url` and `api_key` need to change — your existing application code works without modification. ## Why ZnapAI OpenAI, Gemini, Vertex AI, and Azure — all accessed with a single API key and a unified endpoint. No monthly fees. Pay only for what you use, with competitive rates across all model providers. Drop-in replacement for the OpenAI SDK. Point to `https://api.znapai.com/v1` and keep everything else unchanged. Real-time dashboards for request counts, token usage, latency, and per-model cost breakdown. Enterprise-grade security, data privacy, and SLA-backed uptime for production workloads. 1:1 support from real engineers for integration help, model selection, and performance tuning. ## More resources Connect ZnapAI to Roo Code, Cline, Claude Code, Codex, OpenCode, and more. Check your balance, top up credits, and monitor spend across all providers. Manage API keys, view live usage metrics, and configure your account. # Models Source: https://docs.znapai.com/models One API for hundreds of models Explore and browse every model available through ZnapAI. ## `GET /v1/models` Lists every model your API key can access. ```shellscript cURL theme={null} curl --location 'https://api.znapai.com/v1/models' \ --header 'Authorization: Bearer $ZnapAI_API_KEY' ``` ```json Response theme={null} { "data": [ { "id": "gpt-image-2", "canonical_slug": "gpt-image-2", "name": "gpt-image-2", "created": 1677610602, "description": "", "context_window": null, "max_tokens": null, "mode": "image_generation", "architecture": { "modality": "text+image+file->image", "input_modalities": ["text", "image", "file"], "output_modalities": ["image"] }, "links": {}, "capabilities": { "supports_vision": true, "supports_pdf_input": true }, "pricing": { "prompt": "0.0000025", "completion": "0.000005", "image": "0.000004", "image_output": "0.000015", "input_cache_read": "0.000000625" } }, { "id": "gemini-3.1-flash-lite", "canonical_slug": "gemini-3.1-flash-lite", "name": "gemini-3.1-flash-lite", "created": 1677610602, "description": "", "context_window": 1048576, "max_tokens": 65536, "mode": "chat", "architecture": { "modality": "text+image+audio+file->text", "input_modalities": ["text", "image", "audio", "file"], "output_modalities": ["text"] }, "links": {}, "capabilities": { "supports_system_messages": true, "supports_response_schema": true, "supports_vision": true, "supports_function_calling": true, "supports_tool_choice": true, "supports_prompt_caching": true, "supports_audio_input": true, "supports_audio_output": false, "supports_pdf_input": true, "supports_native_streaming": true, "supports_web_search": true, "supports_url_context": true, "supports_reasoning": true }, "pricing": { "prompt": "0.00000025", "completion": "0.0000015", "audio": "0.0000005", "internal_reasoning": "0.0000015", "input_cache_read": "0.000000025", "web_search": "0.014" } } /* ...remaining models */ ], "total_count": 61, "links": { "next": null } } ``` ## Query Parameters The Models API supports query parameters to filter the list of models returned. ### `mode` Filter models by what they're used for — a comma-separated list. | Value | Description | | --------------------- | --------------------------------------------- | | `chat` | Text and multimodal chat/completion models | | `image_generation` | Models that generate images | | `video_generation` | Models that generate video | | `embedding` | Embedding models | | `rerank` | Reranking models | | `responses` | Models served through the Responses API | | `realtime` | Realtime (low-latency voice/streaming) models | | `audio_speech` | Text-to-speech models | | `audio_transcription` | Speech-to-text models | ```shellscript cURL theme={null} curl --location 'https://api.znapai.com/v1/models?mode=video_generation' \ --header 'Authorization: Bearer $ZnapAI_API_KEY' ``` ```json Response theme={null} { "data": [ { "id": "veo-3.1-generate-preview", "canonical_slug": "veo-3.1-generate-preview", "name": "veo-3.1-generate-preview", "created": 1677610602, "description": "", "context_window": 1024, "max_tokens": null, "mode": "video_generation", "architecture": { "modality": "text->video", "input_modalities": ["text"], "output_modalities": ["video"] }, "links": {}, "pricing": { "prompt": null, "completion": null, "request": null, "image": null, "image_output": null, "audio": null, "audio_output": null, "internal_reasoning": null, "input_cache_read": null, "input_cache_write": null, "input_cache_write_1h": null, "web_search": null } }, { "id": "veo-3.1-fast-generate-preview", "canonical_slug": "veo-3.1-fast-generate-preview", "name": "veo-3.1-fast-generate-preview", "created": 1677610602, "description": "", "context_window": 1024, "max_tokens": null, "mode": "video_generation", "architecture": { "modality": "text->video", "input_modalities": ["text"], "output_modalities": ["video"] }, "links": {}, "pricing": { "prompt": null, "completion": null, "request": null, "image": null, "image_output": null, "audio": null, "audio_output": null, "internal_reasoning": null, "input_cache_read": null, "input_cache_write": null, "input_cache_write_1h": null, "web_search": null } } /* ...remaining video models */ ], "total_count": 6, "links": { "next": null } } ``` ### `output_modalities` Filter models by their output capabilities. Accepts a comma-separated list of modalities. | Value | Description | | ------------ | -------------------------------- | | `text` | Models that produce text output | | `image` | Models that generate images | | `audio` | Models that produce audio output | | `embeddings` | Embedding models | | `video` | Models that generate video | Examples: ```shellscript cURL theme={null} # All models (default) curl --location 'https://api.znapai.com/v1/models' \ --header 'Authorization: Bearer $ZnapAI_API_KEY' # Image generation models only curl --location 'https://api.znapai.com/v1/models?output_modalities=image' \ --header 'Authorization: Bearer $ZnapAI_API_KEY' # Text and image models curl --location 'https://api.znapai.com/v1/models?output_modalities=text,image' \ --header 'Authorization: Bearer $ZnapAI_API_KEY' ``` ```json Response theme={null} { "data": [ { "id": "gpt-image-2", "canonical_slug": "gpt-image-2", "name": "gpt-image-2", "created": 1677610602, "description": "", "context_window": null, "max_tokens": null, "mode": "image_generation", "architecture": { "modality": "text+image+file->image", "input_modalities": ["text", "image", "file"], "output_modalities": ["image"] }, "links": {}, "capabilities": { "supports_vision": true, "supports_pdf_input": true }, "pricing": { "prompt": "0.0000025", "completion": "0.000005", "image": "0.000004", "image_output": "0.000015", "input_cache_read": "0.000000625" } }, { "id": "gpt-5.2", "canonical_slug": "gpt-5.2", "name": "gpt-5.2", "created": 1677610602, "description": "", "context_window": 272000, "max_tokens": 128000, "mode": "chat", "architecture": { "modality": "text+image->text+image", "input_modalities": ["text", "image"], "output_modalities": ["text", "image"] }, "links": {}, "capabilities": { "supports_system_messages": true, "supports_response_schema": true, "supports_vision": true, "supports_function_calling": true /* ...remaining capabilities */ }, "pricing": { "prompt": "0.0000021", "completion": "0.0000084", "input_cache_read": "0.00000021" } } /* ...remaining image-output models */ ], "total_count": 5, "links": { "next": null } } ``` ### Model Object Schema Each model in the `data` array contains the following fields: | Field | Type | Description | | ---------------- | --------------------------- | ------------------------------------------------------------------------------------------------------------------------------- | | `id` | `string` | The model name you pass in API requests (e.g. `"gemini-3.1-flash-lite"`) | | `canonical_slug` | `string` | Always identical to `id` on ZnapAI | | `name` | `string` | Human-readable display name | | `created` | `number` | Unix timestamp of when the model was added | | `description` | `string` | A short description of the model, when available | | `context_window` | `number \| null` | Maximum number of input tokens the model accepts | | `max_tokens` | `number \| null` | Maximum number of output tokens the model can generate | | `mode` | `string \| null` | What the model is used for — `chat`, `image_generation`, `video_generation`, `embedding`, `rerank`, `audio_transcription`, etc. | | `architecture` | `Architecture` | Object describing the model's input/output modalities | | `links` | `object` | Reserved for future use | | `capabilities` | `Capabilities \| undefined` | The model's supported features (omitted if none are known) | | `pricing` | `Pricing \| undefined` | What you pay to use the model, in USD per token (omitted if pricing isn't available) — see [Pricing](#pricing) | ### Architecture Object ```typescript theme={null} { "modality": string, // e.g. "text+image->text" "input_modalities": string[], // e.g. ["text", "image"] "output_modalities": string[] // e.g. ["text"] } ``` * **`input_modalities`** — the types of input the model accepts (text, image, audio, file). * **`output_modalities`** — the types of output the model can produce. ### Capabilities Object The model's supported features, when known — things like `supports_vision`, `supports_function_calling`, `supports_reasoning`, and, for reasoning models, which reasoning effort levels they support (`supports_none_reasoning_effort`, `supports_xhigh_reasoning_effort`, etc.). Omitted entirely if no capability data is available for a model. ## Pricing `pricing` shows what you actually pay to use the model — already reflecting any discounts, in USD per token (or per request, for models like rerank). ### Fields All values are USD amounts per token, formatted as **strings**: | Field | Description | | ---------------------- | ------------------------------------------------------------------------------- | | `prompt` | Cost per input (prompt) token | | `completion` | Cost per output (completion) token | | `request` | Flat cost per request (used by models like rerank instead of per-token pricing) | | `image` | Cost per input image token | | `image_output` | Cost per output image token | | `audio` | Cost per input audio token | | `audio_output` | Cost per output audio token | | `internal_reasoning` | Cost per reasoning token | | `input_cache_read` | Cost per cached input token that's read | | `input_cache_write` | Cost per cached input token that's written | | `input_cache_write_1h` | Cost per cached input token written with a 1-hour cache lifetime | | `web_search` | Cost per web search performed | Fields only appear when they're relevant to a model — for example, image-output models show `image_output`, audio-capable models show `audio`/`audio_output`, and text-only models show neither. For most models, `pricing` is omitted entirely if pricing isn't available. ### Video and rerank models For video generation and rerank models, `pricing` always appears, with `null` for any field that doesn't apply — since these models are often priced in ways (e.g. per-second video) that don't fit the standard per-token fields above. ### `overrides` (long-context pricing) Some models charge more once a request passes a certain prompt length. When that applies, `overrides` lists the higher rates and the token threshold they kick in at: ```json theme={null} "overrides": [ { "min_prompt_tokens": 128000, "prompt": "...", "completion": "..." }, { "min_prompt_tokens": 200000, "prompt": "...", "completion": "...", "input_cache_read": "...", "input_cache_write": "..." } ] ``` Omitted entirely for models without long-context pricing. ### Example response ```json theme={null} { "id": "gemini-3.1-flash-lite", "canonical_slug": "gemini-3.1-flash-lite", "name": "gemini-3.1-flash-lite", "created": 1677610602, "description": "", "context_window": 1048576, "max_tokens": 65536, "mode": "chat", "architecture": { "modality": "text+image+audio+file->text", "input_modalities": ["text", "image", "audio", "file"], "output_modalities": ["text"] }, "links": {}, "capabilities": { "supports_system_messages": true, "supports_response_schema": true, "supports_vision": true, "supports_function_calling": true, "supports_tool_choice": true, "supports_prompt_caching": true, "supports_audio_input": true, "supports_audio_output": false, "supports_pdf_input": true, "supports_native_streaming": true, "supports_web_search": true, "supports_url_context": true, "supports_reasoning": true }, "pricing": { "prompt": "0.00000025", "completion": "0.0000015", "audio": "0.0000005", "internal_reasoning": "0.0000015", "input_cache_read": "0.000000025", "web_search": "0.014" } } ``` A video-generation model, for comparison — note `capabilities` is omitted entirely when no capability data is available for it, while `pricing` still appears with `null` fields: ```json theme={null} { "id": "veo-3.1-generate-preview", "canonical_slug": "veo-3.1-generate-preview", "name": "veo-3.1-generate-preview", "created": 1677610602, "description": "", "context_window": 1024, "max_tokens": null, "mode": "video_generation", "architecture": { "modality": "text->video", "input_modalities": ["text"], "output_modalities": ["video"] }, "links": {}, "pricing": { "prompt": null, "completion": null, "request": null, "image": null, "image_output": null, "audio": null, "audio_output": null, "internal_reasoning": null, "input_cache_read": null, "input_cache_write": null, "input_cache_write_1h": null, "web_search": null } } ``` ## `GET /models` (OpenAI format) Dropping the `v1` prefix returns a lighter, OpenAI-compatible model list — just the `id`, `object`, `created`, and `owned_by` fields, matching the shape returned by OpenAI's own `/models` endpoint. Use this if you're pointing an existing OpenAI SDK or tool at ZnapAI and just need the standard model list. ```shellscript cURL theme={null} curl --location 'https://api.znapai.com/models' \ --header 'Authorization: Bearer $ZnapAI_API_KEY' ``` ```json Response theme={null} { "data": [ { "id": "gpt-image-2", "object": "model", "created": 1677610602, "owned_by": "openai" }, { "id": "gemini-3.1-flash-lite", "object": "model", "created": 1677610602, "owned_by": "openai" }, { "id": "veo-3.1-generate-preview", "object": "model", "created": 1677610602, "owned_by": "openai" } /* ...remaining models */ ] } ``` # OpenAI Embedding Source: https://docs.znapai.com/open-embedding *** ## Request ```shellscript cURL theme={null} curl --location 'https://api.znapai.com/v1/embeddings' \ --header 'Content-Type: application/json' \ --header 'Authorization: Bearer $ZnapAI_API_KEY' \ --data '{ "input": "The food was delicious and the waiter...", "model": "text-embedding-ada-002", "encoding_format": "float" }' ``` ```python OpenAI SDK (Python) theme={null} import openai client = openai.OpenAI( api_key="$ZnapAI_API_KEY", base_url="https://api.znapai.com/" ) response = client.embeddings.create( model="text-embedding-ada-002", input="The food was delicious and the waiter...", encoding_format="float" ) print(response) ``` ```javascript OpenAI SDK (JS) theme={null} import OpenAI from "openai"; const openai = new OpenAI({ apiKey: "$ZnapAI_API_KEY", baseURL: "https://api.znapai.com/" }); const response = await openai.embeddings.create({ model: "text-embedding-ada-002", input: "The food was delicious and the waiter...", encoding_format: "float", }); console.log(response); ``` ## Response ```json theme={null} { "object": "list", "data": [ { "object": "embedding", "embedding": [ 0.0023064255, -0.009327292, 0.001287413, -0.0028842222 ], "index": 0 } ], "model": "text-embedding-ada-002", "usage": { "prompt_tokens": 8, "total_tokens": 8 } } ``` *** ## Parameters Input text to embed, encoded as a string or array of tokens. To embed multiple inputs in a single request, pass an array of strings or array of token arrays. The input must not exceed the max input tokens for the model (8192 tokens for all embedding models), cannot be an empty string, and any array must be 2048 dimensions or less. In addition to the per-input token limit, all embedding models enforce a maximum of 300,000 tokens summed across all inputs in a single request. Supported formats: * `string`: The string that will be turned into an embedding. * `array of strings`: The array of strings that will be turned into an embedding. * `array of numbers`: The array of integers (tokens) that will be turned into an embedding. * `array of arrays of numbers`: The array of arrays containing integers (tokens) that will be turned into an embedding. ID of the model to use. Supported models: * `text-embedding-ada-002` * `text-embedding-3-small` * `text-embedding-3-large` The number of dimensions the resulting output embeddings should have. Only supported in `text-embedding-3` and later models. The format to return the embeddings in. Options: * `float` * `base64` A unique identifier representing your end-user, which can help monitor and detect abuse. *** ## Returns The response is a `CreateEmbeddingResponse` object containing the generated embeddings and usage statistics. The object type, which is always `"list"`. The list of embeddings generated by the model. The object type, which is always `"embedding"`. The embedding vector, which is a list of floats. The length of the vector depends on the model and the `dimensions` parameter. The index of the embedding in the list of embeddings. The name of the model used to generate the embedding. The usage information for the request. The number of tokens used by the prompt. The total number of tokens used by the request. # OpenAI Responses generation Source: https://docs.znapai.com/open-responses *** ## Request ```shellscript cURL theme={null} curl --location 'https://api.znapai.com/v1/responses' \ --header 'Content-Type: application/json' \ --header 'Authorization: Bearer $ZnapAI_API_KEY' \ --header 'spend-logs-metadata: {"user_id": "user-123", "project_id": "proj_abc", "env": "production"}' \ --data '{ "model": "gpt-5-mini", "input": [ { "role": "user", "content": [ { "type": "input_text", "text": "Introduce artificial intelligence" } ] } ] }' ``` ```python OpenAI SDK (Python) theme={null} import openai client = openai.OpenAI( api_key="$ZnapAI_API_KEY", base_url="https://api.znapai.com/" ) response = client.responses.create( model="gpt-5-mini", input=[ { "role": "user", "content": [ { "type": "input_text", "text": "Introduce artificial intelligence" } ] } ] ) print(response) ``` ```javascript OpenAI SDK (JS) theme={null} import OpenAI from "openai"; const openai = new OpenAI({ apiKey: "$ZnapAI_API_KEY", baseURL: "https://api.znapai.com/" }); const response = await openai.responses.create({ model: "gpt-5-mini", input: [ { role: "user", content: [ { type: "input_text", text: "Introduce artificial intelligence", }, ], }, ], }); console.log(response); ``` ## Response ```json theme={null} { "id": "resp_01J8Y...", "object": "response", "created_at": 1741451370, "model": "gpt-5-mini", "status": "completed", "output": [ { "id": "msg_01J8Y...", "role": "assistant", "status": "completed", "type": "message", "content": [ { "type": "output_text", "text": "Artificial intelligence (AI) refers to the simulation of human intelligence in machines that are programmed to think and learn like humans. These machines can perform tasks such as learning, reasoning, problem-solving, perception, and language understanding." } ] } ], "usage": { "prompt_tokens": 12, "completion_tokens": 45, "total_tokens": 57 } } ``` *** ## Parameters An optional header used for spend logging metadata, containing JSON properties like `user_id`, `project_id`, and `env`. Name of the model to use (for example: `gpt-5-mini`). To see the complete list of supported models, visit: [https://znapai.com/models/chat](https://znapai.com/models/chat) The user input. Can be a plain string for simple text prompts, or an array of message objects for multimodal and multi-turn conversations. The role of the message creator. Options: * `user`: User message * `assistant`: AI response (for multi-turn conversations) * `system`: System prompt to guide AI behavior Default: `"user"` An ordered list of content parts. Supports text, images, and files in the same message. The content type. Options: * `input_text`: Text input * `input_image`: Image input (URL or base64) * `input_file`: File input (PDF, DOCX, TXT, CSV, etc.) The text content. Required if `type` is `input_text`. The image URL or base64 data URI. Required if `type` is `input_image`. Supports two formats: 1. **Full image URL**: Publicly accessible URL (e.g., `https://example.com/image.jpg`) 2. **Base64 format**: Complete Data URI (e.g., `data:image/jpeg;base64,{base64_data}`) Supported formats: `jpeg`, `png`, `gif`, `webp`. A publicly accessible URL to a file. Required if `type` is `input_file`. Supported formats: `pdf`, `docx`, `txt`, `csv`, and more. Controls output randomness between 0 and 2. Lower values (like `0.2`) make the output more deterministic, higher values (like `1.8`) make it more creative. Default: `1.0` The maximum number of tokens to generate. Different models have different maximum limits. Whether to stream the response as it is generated (SSE format). Default: `false` Controls diversity via nucleus sampling (range 0 to 1). Recommended to set either `temperature` or `top_p`, but not both. Default: `1.0` Controls reasoning effort for supported models (e.g. `gemini-2.5-flash`, `o3`). The reasoning effort level. Options: `"low"`, `"medium"`, `"high"`. Higher effort produces more thorough reasoning but increases latency and token usage. A list of tools available for the model to extend its capabilities. The tool type to enable. Options: * `web_search_preview`: Real-time internet search * `function`: Call custom functions * `remote_mcp`: Connect to remote Model Context Protocol services The function name. Required when `type` is `"function"`. A description of what the function does. Required when `type` is `"function"`. JSON Schema definition of the function's parameters. Required when `type` is `"function"`. The schema type. Usually `"object"`. A map of parameter names to their schema definitions. List of required parameter names. *** ## Usage examples ### PDF / File understanding Upload or reference a document and ask questions about it. ```json theme={null} { "model": "gpt-4.1", "input": [{ "role": "user", "content": [ { "type": "input_file", "file_url": "https://example.com/report.pdf" }, { "type": "input_text", "text": "Summarize this document" } ] }] } ``` ### Advanced reasoning Use higher reasoning effort for complex tasks. ```json theme={null} { "model": "gemini-2.5-flash", "reasoning": {"effort": "high"}, "input": "Design a scalable architecture for a multi-tenant CRM SaaS." } ``` ### Function calling Allow the model to invoke custom functions. ```json theme={null} { "model": "gpt-5-mini", "tools": [ { "type": "function", "name": "get_weather", "description": "Get weather for a city", "parameters": { "type": "object", "properties": { "city": {"type": "string"} }, "required": ["city"] } } ], "input": "What is the weather in Delhi?" } ``` ### Web search Enable live web search capabilities. ```json theme={null} { "model": "gpt-5-mini", "tools": [{"type": "web_search_preview"}], "input": "What are the latest AI announcements this week?" } ``` ### Image understanding Analyze images and answer questions about them. ```json theme={null} { "model": "gpt-5-mini", "input": [{ "role": "user", "content": [ { "type": "input_text", "text": "Describe this image" }, { "type": "input_image", "image_url": "https://example.com/image.jpg" } ] }] } ``` *** ## Params to Avoid | Param | Reason | | --------------------- | ---------------------------------------------------------------------------------------------------------- | | `messages` | The Responses API uses `input` instead of `messages`. Sending `messages` will result in an error. | | `response_format` | Use structured outputs parameters defined for the Responses API instead of the standard `response_format`. | | `n` | Generating multiple choices is not supported by the Responses API. | | `stream_options` | Not supported by this endpoint. | | `presence_penalty` | Not supported by this endpoint. | | `frequency_penalty` | Not supported by this endpoint. | | `logit_bias` | Not supported by this endpoint. | | `logprobs` | Not supported by this endpoint. | | `top_logprobs` | Not supported by this endpoint. | | `seed` | Not supported by this endpoint. | | `spend-logs-metadata` | This metadata must be passed as an HTTP header, not in the JSON request body | # OpenAI Text generation Source: https://docs.znapai.com/open-text *** ## Request ```shellscript cURL theme={null} curl --location 'https://api.znapai.com/v1/chat/completions' \ --header 'Content-Type: application/json' \ --header 'Authorization: Bearer $ZnapAI_API_KEY' \ --header 'spend-logs-metadata: {"user_id": "user-123", "project_id": "proj_abc", "env": "production"}' \ --data '{ "model": "gpt-4o-mini", "messages": [ { "role": "user", "content": "Hello!" } ] }' ``` ```python OpenAI SDK (Python) theme={null} import openai client = openai.OpenAI( api_key="$ZnapAI_API_KEY", base_url="https://api.znapai.com/" ) completion = client.chat.completions.create( model="gpt-4o-mini", messages = [ { "role": "user", "content": "hello" } ] ) print(completion) ``` ```javascript OpenAI SDK (JS) theme={null} import OpenAI from "openai"; const openai = new OpenAI({ apiKey: "$ZnapAI_API_KEY", baseURL: "https://api.znapai.com/" }); const completion = await openai.chat.completions.create({ model: "gpt-4o-mini", messages: [ { role: "user", content: "hello", }, ] }); console.log(completion); ``` ## Response ```json theme={null} { "id": "chatcmpl-B8rLGf4crBdVhX7a13Ae37NI9h2Re", "created": 1741451370, "model": "gpt-4o-mini", "object": "chat.completion", "system_fingerprint": "fp_ded0d14823", "choices": [ { "finish_reason": "stop", "index": 0, "message": { "content": "Hello! How can I assist you today?", "role": "assistant", "tool_calls": null, "function_call": null } } ], "usage": { "completion_tokens": 9, "prompt_tokens": 9, "total_tokens": 18, "completion_tokens_details": { "accepted_prediction_tokens": 0, "audio_tokens": 0, "reasoning_tokens": 0, "rejected_prediction_tokens": 0 }, "prompt_tokens_details": { "audio_tokens": 0, "cached_tokens": 0 } }, "service_tier": null, "prompt_filter_results": [ { "prompt_index": 0, "content_filter_results": { "hate": { "filtered": false, "severity": "safe" }, "jailbreak": { "filtered": false, "detected": false }, "self_harm": { "filtered": false, "severity": "safe" }, "sexual": { "filtered": false, "severity": "safe" }, "violence": { "filtered": false, "severity": "safe" } } } ] } ``` *** ## Parameters An optional header used for spend logging metadata, containing JSON properties like `user_id`, `project_id`, and `env`. Name of the model to use (for example: gpt-4o-mini). To see the complete list of supported chat models, visit: [https://znapai.com/models/chat](https://znapai.com/models/chat) A list of messages comprising the conversation so far. Role type * `user` - User message * `assistant` - AI response (for multi-turn) * `system` - System prompt Message content Your question or message Example: ```json theme={null} [{"role": "user", "content": "Hello, please introduce yourself"}] ``` Advanced usage: Add system prompt (to define AI behavior): ```json theme={null} [ {"role": "system", "content": "You are a professional Python tutor"}, {"role": "user", "content": "How do I learn programming?"} ] ``` Controls output randomness, range 0-2 * Lower values (e.g., 0.2) make output more deterministic * Higher values (e.g., 1.8) make output more random An alternative to sampling with temperature, called nucleus sampling, where the model considers the results of the tokens with top\_p probability mass. So 0.1 means only the tokens comprising the top 10% probability mass are considered. Maximum number of tokens to generate Different models have different maximum limits, please refer to specific model documentation Number between -2.0 and 2.0. Positive values penalize new tokens based on their existing frequency in the text so far, decreasing the model's likelihood to repeat the same line verbatim. Number between -2.0 and 2.0. Positive values penalize new tokens based on whether they appear in the text so far, increasing the model's likelihood to talk about new topics. How many chat completion choices to generate for each input message. If set, partial message deltas will be sent, like in ChatGPT. Up to 4 sequences where the API will stop generating further tokens. *** ## Params to Avoid | Param | Reason | | --------------------- | ---------------------------------------------------------------------------- | | `stream_options` | Not supported by non-OpenAI models | | `seed` | Not supported by non-OpenAI models | | `logprobs` | Not supported by non-OpenAI models | | `top_logprobs` | Not supported by non-OpenAI models | | `logit_bias` | Not supported by non-OpenAI models | | `spend-logs-metadata` | This metadata must be passed as an HTTP header, not in the JSON request body | # OpenAI Introduction Source: https://docs.znapai.com/openai-intro *** ## OpenAI standard API format supports all models listed at [https://znapai.com/models](https://znapai.com/models) # Vertex Image generation Source: https://docs.znapai.com/vertex-image *** ## Request ```shellscript cURL theme={null} curl --location "https://api.znapai.com/v1beta1/projects/default/locations/global/publishers/google/models/gemini-3.1-flash-image-preview:generateContent" \ --header "Authorization: Bearer $ZnapAI_API_KEY" \ --header "Content-Type: application/json" \ --header 'spend-logs-metadata: {"user_id": "user-123", "project_id": "proj_abc", "env": "production"}' \ --data '{ "contents": [ { "role": "user", "parts": [ { "text": "Generate an image of an F35 flying" } ] } ], "generationConfig": { "candidateCount": 1 } }' ``` ## Response ```json theme={null} { "candidates": [ { "content": { "role": "model", "parts": [ { "inlineData": { "mimeType": "image/png", "data": "iVBORwZP...ggQGt+y0AAAAASUVORK5CYII=" } } ] }, "finishReason": "STOP" } ], "usageMetadata": { "promptTokenCount": 6, "candidatesTokenCount": 1290, "totalTokenCount": 1296, "trafficType": "ON_DEMAND", "promptTokensDetails": [ { "modality": "TEXT", "tokenCount": 6 } ], "candidatesTokensDetails": [ { "modality": "IMAGE", "tokenCount": 1290 } ] }, "modelVersion": "gemini-3.1-flash-image-preview", "createTime": "2026-04-08T17:31:32.596160Z", "responseId": "9JDWacCxJNiipt8Psd7RoQs" } ``` ## Image from base64 data Vertex Image *** ## Parameters An optional header used for spend logging metadata, containing JSON properties like `user_id`, `project_id`, and `env`. The conversation history or input prompts as an array of content objects. The role of the creator of the content (e.g. `"user"` or `"model"`). An ordered list of parts that constitute a single message turn. The text prompt or description for image generation. Instructions to the model that dictate how it should behave. An ordered list of parts that constitute the system instruction. The text of the system instruction. Configuration options for the generation. Number of generated images to return. Controls the randomness of the output. The maximum cumulative probability of tokens to consider when sampling. The maximum number of tokens to consider when sampling. The maximum number of tokens to include in a candidate. A list of sequences that will stop generation. Allowed modalities of the output. Use `["IMAGE", "TEXT"]`. Settings for the output image. Aspect ratio of the generated image (e.g. `"16:9"`, `"1:1"`). Output image resolution level (e.g. `"1K"`, `"2K"`, `"4K"`). A list of unique safety settings for blocking unsafe content. The category for this setting. The threshold for blocking. A list of tools the model may call. Configuration for Google Search grounding. Configuration for tools. Configuration for function calling. The function calling mode (e.g. `AUTO`). *** ## Params to Avoid | Param | Reason | | ------------------------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------- | | `prompt`, `n`, `size`, `quality` | OpenAI/Azure OpenAI parameters; sending these at the root level will fail schema validation. Use `contents` and `generationConfig` instead. | | `response_format`, `output_format` | Not supported by the Gemini API. Response format is determined by `responseModalities`. | | `background`, `output_compression`, `style` | OpenAI/Azure specific parameters; not supported by Gemini models. | | `generationConfig.responseMimeType: "application/json"` | Not supported when `responseModalities` includes `"IMAGE"`. | | `google_search` | Snake case is used in the Gemini Developer API, but the Vertex AI API requires camelCase (`googleSearch`). | | `spend-logs-metadata` | This metadata must be passed as an HTTP header, not in the JSON request body | Ensure you do not mix OpenAI or Azure-specific parameters (such as `prompt`, `size`, `quality`, or `n`) with Gemini/Vertex AI request structure. Vertex AI expects prompt text inside the nested `contents.parts` object using camelCase keys. *** # Vertex Image editing Source: https://docs.znapai.com/vertex-image-edit *** ## Request ```shellscript cURL theme={null} curl --location 'https://api.znapai.com/v1beta1/projects/default/locations/global/publishers/google/models/gemini-2.5-flash-image:generateContent' \ --header 'Authorization: Bearer $ZnapAI_API_KEY' \ --header 'Content-Type: application/json' \ --header 'spend-logs-metadata: {"user_id": "user-123", "project_id": "proj_abc", "env": "production"}' \ --data '{ "contents": [ { "role": "user", "parts": [ { "text": "Edit this image and draw a smiley in it" }, { "inlineData": { "mimeType": "image/jpeg", "data": "/9j/4AAQSkZJRgABAQAAAQABAAD/2wBDABALDA4MChAODQ4SERATGCgaGBYWGDEjJR0oOjM9PDkzODdASFxOQERXRTc4UG1RV19iZ2hnPk1xeXBkeFxlZ2P/2wBDARESEhgVGC8aGi9jQjhCY2NjY2NjY2NjY2NjY2NjY2NjY2NjY2NjY2NjY2NjY2NjY2NjY2NjY2NjY2NjY2NjY2P/wAARCABAAEADASIAAhEBAxEB/8QAHwAAAQUBAQEBAQEAAAAAAAAAAAECAwQFBgcICQoL/8QAtRAAAgEDAwIEAwUFBAQAAAF9AQIDAAQRBRIhMUEGE1FhByJxFDKBkaEII0KxwRVS0fAkM2JyggkKFhcYGRolJicoKSo0NTY3ODk6Q0RFRkdISUpTVFVWV1hZWmNkZWZnaGlqc3R1dnd4eXqDhIWGh4iJipKTlJWWl5iZmqKjpKWmp6ipqrKztLW2t7i5usLDxMXGx8jJytLT1NXW19jZ2uHi4+Tl5ufo6erx8vP09fb3+Pn6/8QAHwEAAwEBAQEBAQEBAQAAAAAAAAECAwQFBgcICQoL/8QAtREAAgECBAQDBAcFBAQAAQJ3AAECAxEEBSExBhJBUQdhcRMiMoEIFEKRobHBCSMzUvAVYnLRChYkNOEl8RcYGRomJygpKjU2Nzg5OkNERUZHSElKU1RVVldYWVpjZGVmZ2hpanN0dXZ3eHl6goOEhYaHiImKkpOUlZaXmJmaoqOkpaanqKmqsrO0tba3uLm6wsPExcbHyMnK0tPU1dbX2Nna4uPk5ebn6Onq8vP09fb3+Pn6/9oADAMBAAIRAxEAPwCxRRRXsHAFFFFABRRRQAUUUUAFFFFABRRRQAUUUUAFFFFABRRRQAUUUUAFFFFABRRRQAUUUUAFFFFABRRRQAUUUUAf/9k=" } } ] } ], "generationConfig": { "responseModalities": ["IMAGE", "TEXT"] } }' ``` ## Input Contents 0 Parts 1 Inline Data Data ## Response ```json theme={null} { "candidates": [ { "content": { "role": "model", "parts": [ { "inlineData": { "mimeType": "image/png", "data": "iVBORw0KGgo...uQmCC" } } ] }, "finishReason": "STOP" } ], "usageMetadata": { "promptTokenCount": 1812, "candidatesTokenCount": 1290, "totalTokenCount": 3102, "trafficType": "ON_DEMAND", "promptTokensDetails": [ { "modality": "TEXT", "tokenCount": 6 }, { "modality": "IMAGE", "tokenCount": 1806 } ], "candidatesTokensDetails": [ { "modality": "IMAGE", "tokenCount": 1290 } ] }, "modelVersion": "gemini-2.5-flash-image", "createTime": "2026-04-08T17:50:54.995975Z", "responseId": "fpXWaYflPLqnpt8P8svDwAE" } ``` *** ## Image from base64 data Candidates 0 Content Parts 0 Inline Data Data (1) *** ## Parameters An optional header used for spend logging metadata, containing JSON properties like `user_id`, `project_id`, and `env`. The conversation history or input prompts as an array of content objects. The role of the creator of the content (e.g. `"user"` or `"model"`). An ordered list of parts that constitute a single message turn. The text instruction prompt for editing. The inline image data to be edited. The IANA media type of the image (e.g. `image/png`, `image/jpeg`). The base64-encoded image bytes. Instructions to the model that dictate how it should behave. An ordered list of parts that constitute the system instruction. The text of the system instruction. A list of `Tools` the model may use to generate the next response. Supported tools are function declarations, code execution, and Google Search. A list of function declarations the model can call. The name of the function to call. A description of what the function does. Describes the parameters for the function in JSON Schema format. The type of the parameters object. Usually `"object"`. A map of parameter names to their schema definitions. List of required parameter names. Enables the model to execute code as part of generation. Pass an empty object `{}` to enable. Tool to support Google Search grounding in model responses. Pass an empty object `{}` to enable. Tool configuration for any `Tool` specified in the request. Configuration for function calling behavior. Controls how the model uses the provided functions. One of: * `"AUTO"` — model decides whether to call a function or respond in text * `"ANY"` — model must call one of the provided functions * `"NONE"` — model must not call any functions Optional. When `mode` is `"ANY"`, limits the model to only call functions from this list. Configuration options for the generation. Number of generated images to return. Controls the randomness of the output. The maximum cumulative probability of tokens to consider when sampling. The maximum number of tokens to consider when sampling. The maximum number of tokens to include in a candidate. A list of sequences that will stop generation. Allowed modalities of the output. Use `["IMAGE", "TEXT"]` to request image output. Settings for the output image. Aspect ratio of the output image (e.g. `"16:9"`, `"1:1"`). Output image resolution level (e.g. `"1K"`, `"2K"`, `"4K"`). A list of unique safety settings for blocking unsafe content. The category for this setting. The threshold for blocking. *** ## Params to Avoid | Param | Reason | | ------------------------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------- | | `prompt`, `n`, `size`, `quality` | OpenAI/Azure OpenAI parameters; sending these at the root level will fail schema validation. Use `contents` and `generationConfig` instead. | | `response_format`, `output_format` | Not supported by the Gemini API. Response format is determined by `responseModalities`. | | `background`, `output_compression`, `style` | OpenAI/Azure specific parameters; not supported by Gemini models. | | `generationConfig.responseMimeType: "application/json"` | Not supported when `responseModalities` includes `"IMAGE"`. | | `inline_data`, `mime_type` | Snake case keys are used in the Google GenAI Developer API, but the Vertex AI API requires camelCase (`inlineData`, `mimeType`). | | `spend-logs-metadata` | This metadata must be passed as an HTTP header, not in the JSON request body | Ensure you do not mix OpenAI or Azure-specific parameters (such as `prompt`, `size`, `quality`, or `n`) with Gemini/Vertex AI request structure. Vertex AI expects prompt text and the image input inside the nested `contents.parts` object using camelCase keys. # Vertex Introduction Source: https://docs.znapai.com/vertex-introduction *** ## Best suited for Google Models ### Text Models * gemini-2.5-pro * gemini-2.5-flash * gemini-2.5-flash-lite * gemini-3.1-pro-preview * gemini-3-flash-preview * \+ more .. ### Image Models * gemini-3.1-flash-image-preview * gemini-3-pro-image-preview * gemini-2.5-flash-image * * more .. # Vertex Text generation Source: https://docs.znapai.com/vertex-text *** ## Request ```shellscript cURL theme={null} curl --location "https://api.znapai.com/v1beta1/projects/default/locations/global/publishers/google/models/gemini-2.5-flash-lite:generateContent" \ --header "Authorization: Bearer $ZnapAI_API_KEY" \ --header "Content-Type: application/json" \ --header 'spend-logs-metadata: {"user_id": "user-123", "project_id": "proj_abc", "env": "production"}' \ --data '{ "contents": [ {"role": "user", "parts": [{"text": "Say hello world"}]} ] }' ``` ## Response ```json theme={null} { "candidates": [ { "content": { "role": "model", "parts": [ { "text": "Hello world" } ] }, "finishReason": "STOP", "avgLogprobs": -4.6243147850036621 } ], "usageMetadata": { "promptTokenCount": 3, "candidatesTokenCount": 2, "totalTokenCount": 32, "trafficType": "ON_DEMAND", "promptTokensDetails": [ { "modality": "TEXT", "tokenCount": 3 } ], "candidatesTokensDetails": [ { "modality": "TEXT", "tokenCount": 2 } ], "thoughtsTokenCount": 27 }, "modelVersion": "gemini-2.5-flash-lite", "createTime": "2026-04-08T17:29:25.479946Z", "responseId": "dZDWacqlHdvzpt8Pud6xqAg" } ``` *** ## Parameters An optional header used for spend logging metadata, containing JSON properties like `user_id`, `project_id`, and `env`. The conversation history or input prompts as an array of content objects. The role of the creator of the content (e.g. `"user"` or `"model"`). An ordered list of parts that constitute a single message turn. The text prompt or response content. System instructions that provide context, rules, or guidelines to the model. An ordered list of parts that constitute the system instruction. The text content of the system instruction. Configuration options for model generation and outputs. Controls the randomness of the output. The maximum cumulative probability of tokens to consider when sampling. The maximum number of tokens to consider when sampling. Number of generated responses to return. The maximum number of tokens to include in a candidate. A list of strings that tell the model to stop generating text. Output response mimetype of the generated candidate text (e.g. `text/plain` or `application/json`). Output response schema of the generated candidate text when `responseMimeType` is `application/json`. Schema must be a subset of the OpenAPI schema. A list of unique safety settings for blocking unsafe content. The category for this setting (e.g. `HARM_CATEGORY_HATE_SPEECH`). Block threshold for this category (e.g. `BLOCK_MEDIUM_AND_ABOVE`). A list of `Tools` the model may use to generate the next response. Supported tools are function declarations, code execution, and Google Search. A list of function declarations the model can call. The name of the function to call. A description of what the function does. Describes the parameters for the function in JSON Schema format. The type of the parameters object. Usually `"object"`. A map of parameter names to their schema definitions. List of required parameter names. Enables the model to execute code as part of generation. Pass an empty object `{}` to enable. Tool to support Google Search grounding in model responses. Pass an empty object `{}` to enable. Tool configuration for any `Tool` specified in the request. Configuration for function calling behavior. Controls how the model uses the provided functions. One of: * `"AUTO"` — model decides whether to call a function or respond in text * `"ANY"` — model must call one of the provided functions * `"NONE"` — model must not call any functions Optional. When `mode` is `"ANY"`, limits the model to only call functions from this list. *** ## Params to Avoid | Param | Reason | | --------------------- | ---------------------------------------------------------------------------- | | `model` | Model is specified in the URL path | | `spend-logs-metadata` | This metadata must be passed as an HTTP header, not in the JSON request body |